-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathLOJ-1040.cpp
49 lines (48 loc) · 1.14 KB
/
LOJ-1040.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
#include<bits/stdc++.h>
using namespace std;
struct edge {
int u,v,w;
edge(int a,int b,int c) {
u=a,v=b,w=c;
}
};
bool comp(edge a,edge b) {
return a.w<b.w;
}
int pr[55];
int parent(int r) {
return (pr[r]==r)?r:pr[r]=parent(pr[r]);
}
int main() {
int t;
freopen("input.txt","r",stdin);
scanf("%d",&t);
for(int z=1; z<=t; z++) {
int n;
scanf("%d",&n);
vector<edge>v;
long long sum1=0,ax;
for(int i=1; i<=n; i++) {
for(int j=1; j<=n; j++) {
scanf("%lld",&ax);
sum1+=ax;
if(i!=j && ax!=0)v.push_back(edge(i,j,ax));
}
}
sort(v.begin(),v.end(),comp);
long long sum2=0,cnt=0,l=v.size();
for(int i=1; i<=n; i++)pr[i]=i;
for(int i=0; i<l; i++) {
int x=parent(v[i].u),y=parent(v[i].v);
if(x!=y) {
pr[x]=y;
sum2+=v[i].w;
cnt++;
if(cnt==(n-1))break;
}
}
if(cnt<(n-1))cout<<"Case "<<z<<": -1\n";
else cout<<"Case "<<z<<": "<<(sum1-sum2)<<"\n";
}
return 0;
}