/* Bismillahir Rahmanir Rahim
Solution using (MST)Kruskal's algorithm.
*/
#include<bits/stdc++.h>
#define fi(n, m) for(int i=n; i<=m; i++)
#define fd(n, m) for(int i=n; i>=m; i--)
using namespace std;
map<string, string>pr;
set<string>st;
set<string>::iterator it;
int ct, n;
struct edge{
string u, v;
int w;
}one[55];
string find(string p){
while(pr[p]!=p){
p=pr[p];
}
return p;
}
bool comp(edge f, edge s){
return f.w<s.w;
}
int mst(int st){
int cnt=0, sm=0;
string xx, yy;
fi(0, n-1){
xx=find(one[i].u);
yy=find(one[i].v);
if(xx!=yy){
pr[yy]=xx;
cnt++;
sm+=one[i].w;
}
if(cnt==ct-1)return sm;
}
return -1;
}
int main(){
int t, cs=1, w, ans;
string u, v;
cin>>t;
while(t--){
cin>>n;
fi(0, n-1){
cin>>u>>v>>w;
st.insert(u);
st.insert(v);
one[i].u=u;
one[i].v=v;
one[i].w=w;
}
for(it=st.begin(); it!=st.end(); it++){
pr[*it]=*it;
}
ct=st.size();
sort(one, one+n, comp);
ans=mst(0);
cout<<"Case "<<cs++<<": ";
if(ans!=-1)cout<<ans<<endl;
else cout<<"Impossible"<<endl;
st.clear();
pr.clear();
}
return 0;
}
|
Monday, February 20, 2017
Solution of Light OJ 1041 - Road Construction
Subscribe to:
Post Comments (Atom)
-
#include<bits/stdc++.h> #define ll long long using namespace std ; ll n , k , t_case ; ll bigmod ( ll b , ll p , ll m...
-
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 ...
-
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 3...
No comments:
Post a Comment