時間限制:1 秒
內存限制:32 兆
特殊判題:否
提交:4397
解決:1921
- 題目描述:
-
某省調查城鎮交通狀況,得到現有城鎮道路統計表,表中列出了每條道路直接連通的城鎮。省政府“暢通工程”的目標是使全省任何兩個城鎮間都可以實現交通(但不一定有直接的道路相連,只要互相間接通過道路可達即可)。問最少還需要建設多少條道路?
- 輸入:
-
測試輸入包含若干測試用例。每個測試用例的第1行給出兩個正整數,分別是城鎮數目N ( < 1000 )和道路數目M;隨後的M行對應M條道路,每行給出一對正整數,分別是該條道路直接連通的兩個城鎮的編號。爲簡單起見,城鎮從1到N編號。
注意:兩個城市之間可以有多條道路相通,也就是說
3 3
1 2
1 2
2 1
這種輸入也是合法的
當N爲0時,輸入結束,該用例不被處理。
- 輸出:
-
對每個測試用例,在1行裏輸出最少還需要建設的道路數目。
- 樣例輸入:
-
4 2 1 3 4 3 3 3 1 2 1 3 2 3 5 2 1 2 3 5 999 0 0
- 樣例輸出:
-
1 0 2 998
import java.util.Arrays; import java.util.Scanner; public class Main{ static int Tree[] = new int[1000]; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); while( scanner.hasNext() ){ Arrays.fill(Tree, -1); int n = scanner.nextInt(); if(n == 0) break; int m = scanner.nextInt(); while(m-- != 0){ int a = scanner.nextInt(); int b = scanner.nextInt(); a = findRoot(a); b = findRoot(b); if(a != b) Tree[a] = b; } int ans = 0; for (int i = 1; i <= n; i++) { if(Tree[i] == -1) ans ++; } System.out.println(ans-1); } } public static int findRoot(int x){ if(Tree[x] == -1) return x; else{ int tmp = findRoot(Tree[x]); Tree[x] = tmp; return tmp; } } } /************************************************************** Problem: 1012 User: yihukurama Language: Java Result: Accepted Time:440 ms Memory:34444 kb ****************************************************************/