-
Notifications
You must be signed in to change notification settings - Fork 0
/
loj1041.cpp
97 lines (79 loc) · 1.44 KB
/
loj1041.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
using namespace std;
#include<iostream>
#include<vector>
#include<cstdio>
#include<cstring>
#include<map>
#include<algorithm>
struct edge
{
int u,v,w;
bool operator < (const edge &p) const
{
return w<p.w;
}
};
vector<edge>graph;
int mp,parent[105];
int parent_find(int u)
{
return (u==parent[u])?u:parent_find(parent[u]);
}
void mst()
{
int count=0,i,ans=0,s=graph.size();
sort(graph.begin(),graph.end());
for(i=1;i<mp;i++)
parent[i]=i;
for(i=0;i<s;i++)
{
int u=parent_find(graph[i].u);
int v=parent_find(graph[i].v);
if(u!=v)
{
parent[u]=v;
count++;
ans+=graph[i].w;
if(count==mp-2)
break;
}
}
if(count==mp-2)
{
printf("%d\n",ans);
}
else
{
printf("Impossible\n");
}
}
int main()
{
int t,i,w,Case=1,n;
string str1,str2;
scanf("%d",&t);
while(t--)
{
map<string,int>m;
graph.clear();
scanf("%d",&n);
mp=1;
while(n--)
{
cin>>str1>>str2;
scanf("%d",&w);
if(!m[str1])
m[str1]=mp++;
if(!m[str2])
m[str2]=mp++;
edge e;
e.u=m[str1];
e.v=m[str2];
e.w=w;
graph.push_back(e);
}
printf("Case %d: ",Case++);
mst();
}
return 0;
}