MST - Kurskal Using MAP + String
UVA - 11710 Expensive Subway
Author : Md.Saiful Islam
***/
#include<stdio.h>
#include<stdlib.h>
#include<map>
#include<string>
#include<string.h>
#include<algorithm>
using namespace std;
int cnt,i,node,edge,sum,u,v,cost;
int rank[410],parent[410],array[79810][3];
char str[15];
map<string,int>flag;
int cmp(const void *a,const void *b)
{
int *x = (int *) a;
int *y = (int *) b;
return *x - *y;
}
int Find_Set(int x)
{
if(x != parent[x] )
parent[x]=Find_Set(parent[x]);
return parent[x];
}
void Link(int x,int y)
{
if(rank[x]>rank[y]) parent[y]=x;
else
{
parent[x]=y;
if(rank[x]==rank[y]) rank[y]=rank[y]+1;
}
}
int main()
{
while(scanf("%d %d",&node,&edge)==2 && (node || edge))
{
for(i=0;i<node;i++)
{
scanf("%s",str);
flag[str]=i+1;
parent[i]=i;
rank[i]=0;
}
sum = cnt = 0;
for(i=0;i<edge;i++)
{
scanf("%s",str);
u = flag[str]-1;
scanf("%s",str);
v = flag[str]-1;
scanf("%d",&cost);
array[i][0]=cost;array[i][1] = u; array[i][2] = v;
}
qsort(array,edge,sizeof(array[0]),cmp);
for(i=0;i<edge;i++)
{
u = array[i][1];
v = array[i][2];
cost = array[i][0];
u = Find_Set(u);
v = Find_Set(v);
if(u!=v)
{
Link(u,v);
cnt++;
sum+=cost;
}
}
scanf("%s",str);
if(cnt!=node-1)
printf("Impossible\n");
else printf("%d\n",sum);
flag.clear();
}
return 0;
}
/*
Input:
3 3
Picadilly
Victoria
Queensway
Picadilly Victoria 2
Queensway Victoria 10
Queensway Picadilly 20
Picadilly
4 2
Picadilly
Victoria
Queensway
Temple
Picadilly Victoria 2
Temple Queensway 100
Temple
Output:
12
Impossible
*/
No comments:
Post a Comment