[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; }
相关文章推荐
- HDU2122--Ice_cream’s world III--最小生成树--kruskal
- hdu 2122 Ice_cream’s world III
- HDU 2122 Ice_cream’s world III(最小生成树Kruskal)
- hdu 2122 Ice_cream’s world III(最小生成树))
- HDU 2122 Ice_cream’s world III 【最小生成树】
- HDU 2122 Ice_cream’s world III
- hdu 2122 Ice_cream’s world III
- hdu 2122 Ice_cream’s world III 最小生成树prim
- hdu 2122:Ice_cream’s world III
- hdu 2122 Ice_cream’s world III(最小生成树)
- hdu 2122 Ice_cream’s world III
- hdu 2122 Ice_cream’s world III(最小生成树)
- hdu 2122 Ice_cream’s world III
- hdu 2122(Ice_cream’s world III)(最小生成树,两种算法都可以)
- hdu 2122 Ice_cream’s world III
- HDU - 2122 Ice_cream’s world III(Kruskal)
- Ice_cream’s world III hdu 2122 最小生成树
- HDU 2122 Ice_cream’s world III
- HDU 2122 Ice_cream’s world III 两种最小生成树算法
- 最小生成树 Prim 算法HDU 2122 Ice_cream’s world III