-
Notifications
You must be signed in to change notification settings - Fork 2
/
1040 - Donation.cpp
83 lines (81 loc) · 1.65 KB
/
1040 - Donation.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
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
#include<bits/stdc++.h>
using namespace std;
#define mx 55
struct Edge
{
int u;
int v;
int cost;
Edge(int a, int b, int c)
{
u = a;
v = b;
cost = c;
}
};
vector<Edge> node;
bool comp(Edge a, Edge b)
{
return a.cost < b.cost;
}
int par[mx];
void init(int n)
{
for(int i=0; i<=n; i++){
par[i] = i;
}
}
int findPar(int a)
{
if(par[a]!= a) par[a] = findPar(par[a]);
return par[a];
}
int kruskal(int n,int sz)
{
init(n);
int ret = 0;
for(int i = 0; i<sz; i++){
int a = node[i].u;
int b = node[i].v;
a = findPar(a);
b = findPar(b);
if(a != b){
ret += node[i].cost;
par[a] = par[b];
}
}
return ret;
}
int main()
{
//freopen("out.txt","w",stdout);
int tc,n,a;
scanf("%d",&tc);
for(int t=1; t<=tc; t++){
scanf("%d",&n);
int total = 0;
for(int i=1; i<=n; i++){
for(int j=1; j<=n; j++){
scanf("%d",&a);
total+=a;
if(a != 0){
node.push_back(Edge(i,j,a));
node.push_back(Edge(j,i,a));
}
}
}
sort(node.begin(), node.end(), comp);
int mst = kruskal(n,node.size());
int ans = total-mst;
int p = findPar(1);
for(int i=2;i<=n; i++){
if(findPar(i) != p){
ans = -1;
break;
}
}
printf("Case %d: %d\n",t,ans);
if(t != tc) node.clear();
}
return 0;
}