-
Notifications
You must be signed in to change notification settings - Fork 25
/
holi_spoj.cpp
57 lines (43 loc) · 902 Bytes
/
holi_spoj.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include<bits/stdc++.h>
using namespace std;
class Graph{
int V;
list<pair<int,int> > *l;
public:
Graph(int v){
V = v;
l = new list<pair<int,int> >[V];
}
void addEdge(int u,int v,int cost,bool bidir=true){
l[u].push_back(make_pair(v,cost));
if(bidir){
l[v].push_back(make_pair(u,cost));
}
}
int dfsHelper(int node,bool *visited,int *count,int &ans){
visited[node] = true;
count[node] = 1;
for(auto neighbour:l[node]){
int v = neighbour.first;
if(!visited[v]){
count[node] += dfsHelper(v,visited,count,ans);
ans += 2*min(count[v],V-count[v])*neighbour.second;
}
}
return count[node];
}
int dfsMain(){
bool *visited = new bool[V]{0};
int *count = new int[V]{0};
int ans = 0 ;
dfsHelper(0,visited,count,ans);
return ans;
}
};
int main(){
Graph g(4);
g.addEdge(0,1,3);
g.addEdge(1,2,2);
g.addEdge(3,2,2);
cout<<g.dfsMain();
}