HDU-3786 题解
找出直系亲属
题目大意
找是否直系亲属,直系亲属关系
Time: 1000 ms
Memory: 32768 kB
解题思路及分析
搜索
注意父子都要搜,一开始只搜了父亲WA了好几发
孩子就的不额外写了,搜不到父亲,直接反过来搜
AC代码
#include <bits/stdc++.h>
using namespace std;
typedef long long llong;
int n, m;
vector<char> par[300];
bool vis[300];
int bfs(char s, char t)
{
queue<char> q;
queue<int> de;
q.push(s);
de.push(0);
while (!q.empty())
{
char x = q.front();
int d = de.front();
q.pop();
de.pop();
if (x == t)
{
return d;
}
for (int i = 0; i < par[x].size(); i++)
{
if (!vis[par[x][i]])
{
vis[par[x][i]] = 1;
q.push(par[x][i]);
de.push(d + 1);
}
}
}
return -1;
}
int main()
{
while (~scanf("%d%d", &n, &m) && n && m)
{
for (int i = 'A'; i <= 'Z'; i++)
{
par[i].clear();
}
char s[10];
for (int i = 0; i < n; i++)
{
scanf("%s", s);
if (s[1] != '-')
par[s[0]].push_back(s[1]);
if (s[2] != '-')
par[s[0]].push_back(s[2]);
}
while (m--)
{
bool f = 0;
scanf("%s", s);
memset(vis, 0, sizeof(vis));
int ans = bfs(s[0], s[1]);
if (ans == -1)
{
memset(vis, 0, sizeof(vis));
ans = bfs(s[1], s[0]);
f = 1;
}
if (ans == -1)
{
printf("-\n");
}
else if (ans == 1)
{
printf(f ? "parent\n" : "child\n");
}
else if (ans == 2)
{
printf(f ? "grandparent\n" : "grandchild\n");
}
else
{
for (int i = 2; i < ans; i++)
{
printf("great-");
}
printf(f ? "grandparent\n" : "grandchild\n");
}
}
}
return 0;
}