间接 tdi 实现 简单 出了 政府 sam 并查集
Input 测试输入包含若干测试用例。每个测试用例的第 1 行给出两个正整数,分别是城镇数目 N (<1000) 和道路数目 M;随后的 M 行对应 M 条道路,每行给出一对正整数,分别是该条道路直接连通的两个城镇的编号。为简单起见,城镇从 1 到 N 编号。
注意: 两个城市之间可以有多条道路相通, 也就是说
3 3
1 2
1 2
2 1
这种输入也是合法的
当 N 为 0 时,输入结束,该用例不被处理。
Output 对每个测试用例,在 1 行里输出最少还需要建设的道路数目。
Sample Input
- 4 2 1 3 4 3 3 3 1 2 1 3 2 3 5 2 1 2 3 5 999 0 0
Sample Output
- 1 0 2 998
- Huge input,
- scanf is recommended.
Hint
- Hint
- #include int f[1005];
- int find(int x) {
- return f[x] == x ? x: f[x] = find(f[x]);
- }
- void join(int x, int y) {
- int fx = find(x),
- fy = find(y);
- if (fx != fy) f[fx] = fy;
- }
- int main() {
- int n,
- m,
- x,
- y,
- c,
- i;
- while (scanf("%d", &n) && n != 0) {
- scanf("%d", &m);
- for (i = 1; i <= n; i++) {
- f[i] = i;
- }
- for (i = 1; i <= m; i++) {
- scanf("%d%d", &x, &y);
- if (x < y) join(y, x);
- else join(x, y);
- }
- c = 0;
- for (i = 1; i <= n; i++) {
- if (find(i) == i) c++; //WA教训。。一定是find(i)不是f[i]
- }
- printf("%d\n", c - 1);
- }
- return 0;
- }
畅通工程 - 并查集
来源: http://www.bubuko.com/infodetail-2212844.html