hdu 1233 还是畅通工程
2014-07-26 22:06
218 查看
<h1 style="color:#1A5CC8"> 还是畅通工程</h1><strong><span style="font-family:Arial;font-size:12px;color:green;font-weight:bold;">Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) Total Submission(s): 25547 Accepted Submission(s): 11347 </span></strong> <div class="panel_title" align="left">Problem Description</div> <div class="panel_content">某省调查乡村交通状况,得到的统计表中列出了任意两村庄间的距离。省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可),并要求铺设的公路总长度为最小。请计算最小的公路总长度。 </div><div class="panel_bottom"> </div> <div class="panel_title" align="left">Input</div> <div class="panel_content">测试输入包含若干测试用例。每个测试用例的第1行给出村庄数目N ( < 100 );随后的N(N-1)/2行对应村庄间的距离,每行给出一对正整数,分别是两个村庄的编号,以及此两村庄间的距离。为简单起见,村庄从1到N编号。 当N为0时,输入结束,该用例不被处理。 </div><div class="panel_bottom"> </div> <div class="panel_title" align="left">Output</div> <div class="panel_content">对每个测试用例,在1行里输出最小的公路总长度。 </div><div class="panel_bottom"> </div> <div class="panel_title" align="left">Sample Input</div><div class="panel_content"><pre><div style="font-family:Courier New,Courier,monospace;">3 1 2 1 1 3 2 2 3 4 4 1 2 1 1 3 4 1 4 1 2 3 3 2 4 2 3 4 5 0</div>
Sample Output
3 5 HintHint Huge input, scanf is recommended.<pre name="code" class="html">经典的kruskal算法,数据的特殊性有个小技巧,先用并查集将已经存在的路,节点进行路径压缩到同一个父节点,然后再用kruskal就可以了,注意:不要用cin,会超时#include<iostream> #include<cstdio> #include<queue> using namespace std; #define N 105 struct node{ int from; int to; int value; node (int i=0,int j=0,int k=0){ from=i; to=j; value=k; } }; priority_queue<node> p; bool operator< (const node&x,const node &y){ return x.value>y.value; } int n; int father ; int ans; void kruskal(); int find(int x); void union_set(int a,int b,int c); int main(){ int a,b,c,d; int i,j; freopen("1.txt","r",stdin); while(scanf("%d",&n)!=EOF){ if (n==0) break; for (i=0;i<N;i++){ father[i]=i; } for (i=0;i<n*(n-1)/2;i++){ scanf("%d%d%d%d",&a,&b,&c,&d); if (d){ father[find(b)]=find(a);//路径压缩(这里是关键) } p.push(node(a,b,c)); } ans=0; kruskal(); cout<<ans<<endl; } } void kruskal(){ while (!p.empty()){ node temp=p.top(); p.pop(); union_set(find(temp.from),find(temp.to),temp.value); } } int find(int x){ if (x!=father[x]) father[x]=find(father[x]); return father[x]; } void union_set(int a,int b,int c){ if (a==b) return; father[b]=a; ans+=c; }
[code]
相关文章推荐
- HDU 1233 还是畅通工程
- HDU 1233 还是畅通工程
- 杭电Hdu 1233 还是畅通工程
- hdu1233——还是畅通工程(最小生成树)
- 还是畅通工程(HDU 1233)
- hdu 1233 还是畅通工程(最小生成树)
- hdu 1233 还是畅通工程
- hdu 1233 还是畅通工程(最小生成树prim)
- HDU-1233 还是畅通工程 (最小生成树)
- hdu 1233 还是畅通工程(最小生成树Kruskal)
- HDU - 1233 - 还是畅通工程 (最小生成树!!)
- HDU-OJ-1233 还是畅通工程
- Hdu 1233 还是畅通工程
- HDU 1233--还是畅通工程
- hdu 1233 还是畅通工程(最小生成树,基础)
- hdu 1233 还是畅通工程(最小生成树的Prim和Kruskal两种算法的c++实现)(prim算法详解)
- HDU - 1233 还是畅通工程(最小生成树)
- HDU 1233 还是畅通工程
- HDU 1233 还是畅通工程(最小生成树)
- HDU 1233 还是畅通工程