ACM: 畅通工程-并查集-解题报告
生活随笔
收集整理的這篇文章主要介紹了
ACM: 畅通工程-并查集-解题报告
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
暢通工程
Time Limit:2000MS Memory Limit:32768KB 64bit IO Format:%I64d & %I64u
Description某省調查城鎮交通狀況,得到現有城鎮道路統計表,表中列出了每條道路直接連通的城鎮。省政府“暢通工程”的目標是使全省任何兩個城鎮間都可以實現交通(但不一定有直接的道路相連,只要互相間接通過道路可達即可)。問最少還需要建設多少條道路? Input測試輸入包含若干測試用例。每個測試用例的第1行給出兩個正整數,分別是城鎮數目N ( < 1000 )和道路數目M;隨后的M行對應M條道路,每行給出一對正整數,分別是該條道路直接連通的兩個城鎮的編號。為簡單起見,城鎮從1到N編號。
注意:兩個城市之間可以有多條道路相通,也就是說
3 3
1 2
1 2
2 1
這種輸入也是合法的
當N為0時,輸入結束,該用例不被處理。 Output對每個測試用例,在1行里輸出最少還需要建設的道路數目。 Sample Input4 2 1 3 4 3 3 3 1 2 1 3 2 3 5 2 1 2 3 5 999 0 0Sample Output1 0 2 998
HintHint Huge input, scanf is recommended.
水題,裸并查集,沒什么好說,AC代碼: #include"iostream" #include"cstdio" #include"algorithm" #include"cmath" #include"cstring" using namespace std;int pe[100000]; int num;int find(int x) {return pe[x]==x?x:(pe[x]=find(pe[x])); }int main() {int n,m,a,b;while(~scanf("%d",&n)) {if(!n)break;scanf("%d",&m); num=n-1;for(int i=1; i<=n; i++) {pe[i]=i;}for(int i=0; i<m; i++) {scanf("%d%d",&a,&b);int root1=find(pe[a]);int root2=find(pe[b]);if(root1!=root2) {pe[root2]=root1;num--; }}printf("%d\n",num);}return 0; }
水題,裸并查集,沒什么好說,AC代碼: #include"iostream" #include"cstdio" #include"algorithm" #include"cmath" #include"cstring" using namespace std;int pe[100000]; int num;int find(int x) {return pe[x]==x?x:(pe[x]=find(pe[x])); }int main() {int n,m,a,b;while(~scanf("%d",&n)) {if(!n)break;scanf("%d",&m); num=n-1;for(int i=1; i<=n; i++) {pe[i]=i;}for(int i=0; i<m; i++) {scanf("%d%d",&a,&b);int root1=find(pe[a]);int root2=find(pe[b]);if(root1!=root2) {pe[root2]=root1;num--; }}printf("%d\n",num);}return 0; }
轉載于:https://www.cnblogs.com/HDMaxfun/p/5700725.html
總結
以上是生活随笔為你收集整理的ACM: 畅通工程-并查集-解题报告的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 网站访问过程理解(一点记录)
- 下一篇: ---随心买统计查询