UVA 11710 Solution- Expensive subway
/* Solved by using Kruskal */
/*
uva ID: shoaib05.
Accepted Time: 1.04
*/
#include<iostream>
#include<map>
#include<string>
#include<cstdio>
#include<algorithm>
using namespace std;
typedef struct list
{
int src;
int dest;
int wgt;
};
list arr[79810];
int parent[410];
bool cmp(list x,list y)
{
return x.wgt<y.wgt;
}
int find(int x)
{
while(parent[x]!=x)
x=parent[x];
return x;
}
int main()
{
int edge,node,i,w,u,v,expected_edge,up,vp,cost;
string str,s;
map<string,int> mymap;
while(true)
{
cin>>node>>edge;
if(edge==0 && node==0)
break;
mymap.clear();
for(i=1;i<=node;i++)
{
cin>>str;
mymap[str]=i;
}
for(i=0;i<edge;i++)
{
cin>>str>>s>>w;
arr[i].src=mymap[str];
arr[i].dest=mymap[s];
arr[i].wgt=w;
}
cin>>str;
sort(arr,arr+edge,cmp);
for(i=1;i<=node;i++)
parent[i]=i;
expected_edge=node-1;
cost=0;
for(i=0;i<edge && expected_edge>0;i++)
{
u=arr[i].src;
v=arr[i].dest;
up=find(u);
vp=find(v);
if(up!=vp)
{
expected_edge--;
parent[vp]=up;
cost+=arr[i].wgt;
}
}
if(expected_edge==0)
cout<<cost<<endl;
else
cout<<"Impossible"<<endl;
}
return 0;
}
Comments
Post a Comment