-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMatrix.cpp
More file actions
125 lines (91 loc) · 1.91 KB
/
Matrix.cpp
File metadata and controls
125 lines (91 loc) · 1.91 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
struct data
{
int u,v,cost;
bool operator < (const data &p)const{
return cost > p.cost;
}
};
vector <data> v;
int node,k,source,machine;
int parent[100001];
bool compare(data a,data b)
{
return a.cost > b.cost;
}
void initParent()
{
for(int i=0;i<node;i++)
parent[i]=i;
}
void makeset(int n)
{
parent[n]=n;
}
int find(int x){
if(parent[x]==x) return x;
else if(parent[x]==-1) return -1;
return parent[x] = find(parent[x]);
}
int mst()
{
//makeset(source);
int count = 0,cost=0;
for(int i = 0; i < v.size(); i++)
{
//printf("%d %d %d\n",v[i].u,v[i].v,v[i].cost);
int x = find(v[i].u);
int y = find(v[i].v);
//printf("X=> %d y=> %d\n",x,y);
if(x != y)
{
if(y==-1)
parent[x] = y;
else //if(x==-1)
parent[y]=x;
//printf("New Parent %d=> %d %d=> %d\n",v[i].u,parent[x],v[i].v,parent[y]);
/*else
parent[x] = y;
count++;
cost+= v[i].cost;
if(count == node-1)
break;*/
}
else{
cost+=v[i].cost;
//printf("Cost increased %d\n",cost);
}
}
return cost;
}
int main() {
scanf("%d %d",&node,&machine);
initParent();
for(int i = 0; i<node-1; i++)
{
data d;
scanf("%d %d %d",&d.u,&d.v,&d.cost);
v.push_back(d);
}
sort(v.begin(),v.end());
/*printf("\n");
for(int i = 0; i < v.size(); i++)
{
printf("%d %d %d\n",v[i].u,v[i].v,v[i].cost);
}*/
for(int i = 0; i< machine; i++)
{
int m;
scanf("%d",&m);
parent[m]=-1;
}
//scanf("%d",&source);
int res = mst();
cout << res;
return 0;
}