csu 1010 Water Drinking

并查集变种;

# include <stdio.h>
# include <memory.h>

# define MAXN 100005

int pre[MAXN];
int dis[MAXN];

int main()
{
int n, x, y, i, mind, ans;

while (~scanf("%d", &n))
{
memset(dis, 0, sizeof(dis));
for (i = 0; i < MAXN; ++i)
pre[i] = i;
while (n--)
{
scanf("%d%d", &x, &y);
pre[y] = x;
dis[x] = 1;
}
for (mind = MAXN, ans = i = 0; i < MAXN; ++i)
if (!dis[i])
{
x = i;
while (pre[x] != x)
{
x = pre[x];
++dis[i];
}
if (!x && dis[i] < mind)
{
mind = dis[i];
ans = i;
}
}
printf("%d\n", ans);
}

return 0;
}

下面的程序有一个特别严重的小错误。

View Code
 1 # include <stdio.h>
2 # include <memory.h>
3
4 # define MAXN 100005
5
6 int pre[MAXN];
7 int dis[MAXN];
8
9 int main()
10 {
11 int n, x, y, i, maxn, mind, ans;
12
13 while (~scanf("%d", &n))
14 {
15 memset(dis, 0, sizeof(dis));
16 for (i = 0; i < MAXN; ++i)
17 pre[i] = i;
18 while (n--)
19 {
20 scanf("%d%d", &x, &y);
21 pre[y] = x;
22 dis[x] = 1;
23 maxn = (x>y ? x:y);
24 }
25 for (mind = maxn+1, ans = i = 0; i <= maxn; ++i)
26 if (!dis[i])
27 {
28 x = i;
29 while (pre[x] != x)
30 {
31 x = pre[x];
32 ++dis[i];
33 }
34 if (!x && dis[i] < mind)
35 {
36 mind = dis[i];
37 ans = i;
38 }
39 }
40 printf("%d\n", ans);
41 }
42
43 return 0;
44 }



你可能感兴趣的:(water)