您的位置:首页 > 其它

[MST]hdu 2122 Ice_cream’s world III

2012-08-15 00:24 267 查看
/**
[MST]hdu 2122 Ice_cream’s world III
先一边DFS看图是否联通,然后裸的MST
*/
#include <stdio.h>
#include <string.h>
#include <vector>
#include <algorithm>
using namespace std;
#define N 1024
#define M 10000

vector<int> vec
;
int f
,r
;
struct Edge
{
int u,v,c;
void input()
{
scanf("%d%d%d",&u,&v,&c);
vec[u].push_back(v);
vec[v].push_back(u);
}
}edge[M];

int getF(int x)
{
return x == f[x] ? x : getF(f[x]);
}
void unionSet(int x,int y)
{
if(r[x] > r[y])
f[y] = x;
else
{
f[x] = y;
if(r[x] == r[y])
r[y] ++;
}
}
int vis
;
int n,m,cnt;

void dfs(int u)
{
vis[u] = 1;
++cnt;
for(int i = 0; i < vec[u].size(); ++i)
if(vis[vec[u][i]] == 0)
dfs(vec[u][i]);
}
bool cmp(Edge a,Edge b)
{
return a.c < b.c;
}
int main()
{
int i,j;
while(scanf("%d%d",&n,&m) == 2)
{
for(i = 0; i < n; ++i)
vec[i].clear(),f[i] = i,r[i] = 0;
for(i = 0; i < m; ++i)
edge[i].input();
cnt = 0;
memset(vis,0,sizeof(vis));
dfs(0);
if(cnt != n)
{
printf("impossible\n\n");
continue;
}
int x,y,res = 0;
sort(edge,edge+m,cmp);
for(i = 1,j = 0; i < n; ++j)
{
x = getF(edge[j].u);
y = getF(edge[j].v);
if(x != y)
{
++i;
res += edge[j].c;
unionSet(x,y);
}
}
printf("%d\n\n",res);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: