连接电脑
Time Limit:1000MS Memory Limit:65536K
Total Submit:69 Accepted:24
Description
Description:
机房里有若干台电脑,其中有一些电脑已经相互连接。如果A和B通过网线相连,并且B与C也通过网线相连,那么即便A和C之间没有直接的网线相连,也可以认为A和C是相连的。由于机房里的布线比较乱,并不是所有电脑都相互连通,请问在不变动当前布线情况下,最少要购买几条网线才能使得机房所有电脑都两两连通。
Input
Input:
多组数据。每组数据第一行为整数N,M。N是电脑数量,M是机房已布置好的网线数量。接下来M行,每行为整数A,B。表明A,B之间通过一条网线直接相连。这里可以认为网线是不分方向的,即A->B等价于B->A。
(0 < N <= 200,0 <= M <= 10000,0 < A,B <= N 。) N=0和M=0为输入结束,不需要处理。
Output
Output:
每组一个整数,即最少还要购买几根网线。
Sample Input
Sample Input:
4 2
1 2
2 3
4 0
1 0
0 0
Sample Output
Sample Output:
1
3
0
Source
ahstu@ICPC01
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AK1016 {
class Program {
static void Main(string[] args) {
string jt;
while ((jt = Console.ReadLine()) != null) {
string[] s = jt.Split();
int n = int.Parse(s[0]), m = int.Parse(s[1]);
if (m + n == 0) break;
if (m == 0 && n != 0) { Console.WriteLine(n - 1); continue; }
string[] b = Console.ReadLine().Split();
int[] a = new int[205];
int count = 1;
a[int.Parse(b[0])] = count;
a[int.Parse(b[1])] = count;
for (int i = 1; i < m; i++) {
string[] sb = Console.ReadLine().Split();
int p = int.Parse(sb[0]), q = int.Parse(sb[1]);
if (a[p] != 0) a[q] = count;
else if (a[q] != 0) a[p] = count;
else {
count++;
a[p] = count;
a[q] = a[p];
}
}
for (int i = 1; i <= n; i++)
if (a[i] == 0)
count++;
Console.WriteLine(count - 1);
}
}
}
}