In nature, there are alimentary chains. At the basis of this chain, we generally have the vegetals. Small animals eat those vegetals and bigger animals eat the smaller. There can be cycles in the chain, as when some animal dies he starts a decomposition process which will transform its body into minerals that are a source of energy for the vegetals.
In this problem you will have to find the largest alimentary chain for a given group of creatures. You can consider that if A is predator of B then they are in the same chain.
Input
The input file contains several input sets. The description of each set is given below:
Each set starts with two integers C (1 ≤ C ≤ 5000), the number of creatures, and R (0 ≤ R ≤ 5000), the number of relations. Follow C lines with the names of the creatures, each consisting of lower case letters (a, b, . . . , z). No name is longer than 30 letters. Then there will be R lines describing the relations. Each line will have 2 names of creatures, meaning that the second creature is a predator of the first one.
You can assume that no creature is a predator of himself.
Input is terminated by a set where C = R = 0. This set should not be processed. There is a blank line beteween two input sets.
Output
For each input set produce one line of output, the size of the largest alimentary chain.
Sample Input
5 2
caterpillar
bird
horse
elefant
herb
herb caterpillar
caterpillar bird
0 0
Sample Output
3
问题链接:UVA10685 Nature
问题简述:(略)
问题分析:
自然界中存在食物链的捕食关系,求最大的食物链圈的大小。
简单的并查集问题,看代码不解释。需要在并查集模板上增加数组freq[],并进行相应的计算。
程序说明:(略)
参考链接:(略)
题记:(略)
AC的C++语言程序如下:
/* UVA10685 Nature */
#include <bits/stdc++.h>
using namespace std;
const int N = 10000;
int f[N], freq[N];
void UFInit(int n)
{
for(int i = 0; i < n; i++)
f[i] = i, freq[i] = 0;
}
int Find(int a) {
return a == f[a] ? a : f[a] = Find(f[a]);
}
void Union(int a, int b)
{
a = Find(a);
b = Find(b);
if (a != b) {
f[a] = b;
}
}
int main()
{
int n, m;
while(~scanf("%d%d", &n, &m) && (n || m)) {
getchar();
map<string, int> mp;
string s, u, v;
UFInit(n);
int ccnt = 0;
for(int i = 1; i <= n; i++) {
getline(cin, s);
if(mp.find(s) == mp.end())
mp[s] = ccnt++;
}
for(int i = 1; i <= m; i++) {
cin >> u >> v;
Union(mp[u], mp[v]);
}
int maxac = -1;
for(int i = 0; i < n; i++)
freq[Find(i)]++;
for(int i = 0; i < n; i++)
maxac = max(maxac, freq[i]);
printf("%d\n", maxac);
}
return 0;
}