HDOJ 2473 并查集

就知道会超时,时限 8ms,1 ≤ N ≤ 105 , 1 ≤ M ≤ 106,循环查找当然超时;

有点新意的并查集。

 1 # include <stdio.h>
2
3 # define MAXN 100005
4
5 int father[MAXN];
6
7 int main()
8 {
9 int N, M, i, cnt, ch, x, y, f, tmp, p, clo = 0;;
10
11 while (1)
12 {
13 scanf("%d%d", &N, &M);
14 getchar();
15 if (!N && !M) break;
16 cnt = 0;
17 for (i = 1; i <= N; ++i)
18 father[i] = i;
19 while (M--)
20 {
21 ch = getchar();
22 if (ch == 'M')
23 {
24 scanf("%d%d", &x, &y);
25 getchar();
26 while (x != father[x]) x = father[x];
27 while (y != father[y]) y = father[y];
28 if (x != y)
29 {
30 ++cnt;
31 father[y] = x;
32 }
33 }
34 else if (ch == 'S')
35 {
36 scanf("%d", &x);
37 getchar();
38 if (x != father[x])
39 {
40 tmp = father[x];
41 for (i = 1; i <= N; ++i)
42 if (father[i] = x) father[i] = tmp;
43 father[x] = x;
44 --cnt;
45 }
46 else
47 {
48 f = 1;
49 for (i = 1; i <= N; ++i)
50 if (father[i] = x)
51 {
52 if (f) {father[i] = i; p = i; f = 0;}
53 else father[i] = p;
54 }
55 father[x] = x;
56 if (!f) --cnt;
57 }
58 }
59 }
60 getchar();
61 printf("Case #%d: %d\n", ++clo, N-cnt);
62 }
63
64 return 0;
65 }
原文地址:https://www.cnblogs.com/JMDWQ/p/2404814.html