体会其中精髓的递归路径压缩算法
// Poj 1703, wrote by Dream 2011/2/22
#include <iostream>
using namespace std;
int s[100002];
int f[100002];
int T, N, M;
void Union(int x, int y);
int FindFather(int x);
void PrintResult(int x, int y);
void AddRelation(int x, int y);
int main(int argc, char *argv[])
{
T = 0;
scanf("%d", &T);
for (int i = 0; i < T; ++i)
{
N = M = 0;
scanf("%d %d", &N, &M);
for (int k = 0; k <= N; ++k)
{
s[k] = k;
f[k] = 0;
}
char c = '/0';
int x = 0;
int y = 0;
for (int j = 0; j < M; ++j)
{
scanf("/n%c %d %d", &c, &x, &y);
if (c == 'A')
{
PrintResult(x,y);
}
else // c == 'D'
{
AddRelation(x,y);
}
}
}
return 0;
}
void AddRelation(int x, int y)
{
// x,y both have no message in f[]
if (f[x] == 0 && f[y] == 0)
{
f[y] = x;
f[x] = y;
}
else if (f[x] == 0)
{
f[x] = y;
Union(x,f[y]);
}
else if (f[y] == 0)
{
f[y] = x;
Union(y,f[x]);
}
else
{
Union(x,f[y]);
Union(y,f[x]);
}
}
void PrintResult(int x, int y)
{
if (FindFather(x) == FindFather(y))
{
printf("In the same gang./n");
}
else if (FindFather(x) == FindFather(f[y]))
{
printf("In different gangs./n");
}
else
{
printf("Not sure yet./n");
}
}
void Union(int x, int y)
{
x = FindFather(x);
y = FindFather(y);
if (x == y)
{
return;
}
s[y] = x;
}
//精髓的递归路径压缩算法
int FindFather(int x)
{
if (s[x] != x)
{
s[x] = FindFather(s[x]);
}
return s[x];
/*
这种写没有路径压缩,会导致超时
why the code here will TLE
if (s[x] != x)
{
return FindFather(s[x]);
}
else
return s[x];
*/
}