hdu 1879(并查集+克鲁斯卡尔)
2017-11-20 21:22
323 查看
//并查集 克鲁斯卡尔 #include <iostream> #include<cstdio> #include<algorithm> #include<cstring> using namespace std; const int maxv=100+5; const int maxe=5000+5; struct Edge{ int from,to,weight; }; bool operator<(const Edge &E1,const Edge &E2) { return E1.weight<E2.weight; } Edge edges[maxe]; int parent[maxv]; int find(int x) { return x==parent[x]?x:parent[x]=find(parent[x]); } int kruskal(int pos) { sort(edges,edges+pos); int sum=0; for(int i=0;i<pos;i++) { int cost=edges[i].weight; int p1=find(edges[i].from); int p2=find(edges[i].to); if(p1==p2) continue; parent[p1]=p2; sum+=cost; } return sum; } int main() { int n; while(scanf("%d",&n)==1&&n) { for(int i=1;i<=n;i++) { parent[i]=i; //并查集初始化 } int v1,v2,cost,flag; int pos=n*(n-1)/2; for(int i=0;i<pos;i++) { scanf("%d%d%d%d",&v1,&v2,&cost,&flag); if(flag) { parent[v1]=v2; //合并 } edges[i].from=v1; edges[i].to=v2; edges[i].weight=cost; } cout<<kruskal(pos)<<"\n"; } return 0; }
相关文章推荐
- HDU 1879 继续畅通工程 (Prim(普里姆算法)+Kruskal(克鲁斯卡尔))
- HDU 3371 Connect the Cities (最小生成树 并查集+克鲁斯卡尔)
- HDU-3938 Portal 克鲁斯卡尔思想 (离线并查集)
- HDU 1879 继续畅通工程 (克鲁斯卡尔_最小生成树)
- hdu-1879-继续畅通工程(克鲁斯卡尔求最小生成树)
- hdu1102 克鲁斯卡尔+并查集
- 深度优先DFS和广度优先BFS,破圈法,拓扑序列,prim,克鲁斯卡尔等生成算法(需要用到并查集)迪杰斯特拉算法和弗洛伊德的总结
- HDU 1875 畅通工程再续 (克鲁斯卡尔_最小生成树)
- hdu1879(并查集)
- hdu 1679 The Unique MST (克鲁斯卡尔)
- HDU 1879继续畅通工程(并查集)
- HDU 1233 还是畅通工程 (克鲁斯卡尔_最小生成树+贪心)
- hdu-1162-Eddy's picture(克鲁斯卡尔求最小生成树)
- HDU——1233还是畅通工程(克鲁斯卡尔+优先队列)
- 51nod 1640天气晴朗的魔法(克鲁斯卡尔,并查集)
- hdu 1879_并查集_最小生成树_Kruskal
- 最小生成树——— 克鲁斯卡尔 hdu 1162 Eddy's picture
- PKUACM 2018 D chocolate【并查集+克鲁斯卡尔】
- HDU-1879-继续畅通工程(并查集)
- hdu1879 继续畅通工程(最小生成树、 并查集)