-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathGraphProblem.txt
More file actions
63 lines (57 loc) · 1.64 KB
/
GraphProblem.txt
File metadata and controls
63 lines (57 loc) · 1.64 KB
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
58
59
60
61
62
63
int Solution::solve(int A, vector<vector<int> > &B) {
int m=B.size(),mw=INT_MAX,idx;
vector<pair<int,int>> *l=new vector<pair<int,int>> [A+1];
for(int i=0;i<m;i++)
{
l[B[i][0]].push_back(make_pair(B[i][1],B[i][2]));
l[B[i][1]].push_back(make_pair(B[i][0],B[i][2]));
if(B[i][2]<mw)
{
mw=B[i][2];
idx=B[i][0];
}
}
int weights[A+1];
int parents[A+1];
for(int i=1;i<=A;i++)
{
parents[i]=-1;
weights[i]=INT_MAX;
}
int visited[A+1]={0};
weights[mw]=0;
set<pair<int,int>> st;
st.insert(make_pair(0,idx));
while(!st.empty())
{
pair<int,int> p=*st.begin();
st.erase(st.begin());
for(auto nbr:l[p.second])
{
int v=nbr.first;
int w=nbr.second;
if( visited[v]==0 && w<weights[v])
{
parents[v]=p.second;
//weights[v]=w;
auto it=st.find(make_pair(weights[v],v));
if(it!=st.end())
st.erase(it);
weights[v]=w;
st.insert(make_pair(w,v));
}
}
visited[p.second]=1;
}
int ans=0;
for(int i=1;i<=A;i++)
{
if(parents[i]!=-1)
{
ans+=weights[i];
cout<<weights[i]<<" \n";
cout<<i<<":"<<parents[i]<<"\n";
}
}
return ans;
}