hdu 1232 畅通工程<java>

来源:互联网 发布:服装店销售软件 编辑:程序博客网 时间:2024/06/05 19:48

http://acm.hdu.edu.cn/showproblem.php?pid=1232

题目题意给出城市个数,及已联通城市,求连通图需要再建几条路并查集

import java.util.Scanner;           public class Main {         public static void main(String[] args) {         int m,n,i,a,b,t;         Scanner oo=new Scanner(System.in);         while(oo.hasNext()){             n=oo.nextInt();             if(n==0){break;}             m=oo.nextInt();             int pre[]=new int[n+1];             for(i=1;i<=n;i++){                 pre[i]=i;             }             t=n-1;             for(i=0;i<m;i++){                 a=oo.nextInt();                 b=oo.nextInt();                 while(a!=pre[a]){                     a=pre[a];                 }                 while(b!=pre[b]){                     b=pre[b];                 }                 if(a!=b){                     pre[a]=pre[b];                     t--;                 }             }             System.out.println(t);         }      }  } 


原创粉丝点击