题目解析
就是给你个人,并告诉你这个人中第个人的编号,性别,父亲编号,母亲编号(只不过父亲母亲可能为不存在)
解题思路
我们可以想象的是把自己当作一个根节点,父母当作子节点的去遍历
然后呢,需要判断当前这个节点有没有被用过,用过则是五服之内的
怎么知道是大于五服呢,也就是当前这个人遍历超过4次的
第4次正好是五服

↑ 这样5和7就是五服之内

↑这样子6和7就是五福之外了

↑这样子6和7也是五福之外的
谓高祖父、曾祖父、祖父、父亲、自身五代
注: 本题java最后一个点我怎么都过不了
代码
import java.io.*;
import java.math.*;
import java.util.*;
public class Main
{
static int N = (int) 1e5;
// 存储当前节点i的父母节点
static ArrayList<Integer> fa[] = new ArrayList[N + 10];
// 存储当前节点的性别
static String sex[] = new String[N + 10];
// 存储当前节点是否被用过
static boolean vis[] = new boolean[N + 10];
static boolean check = true;
static void dfs(int u, int depth)
{
// 大于等于4的话 就是超过五服的了
// 不需要再次去遍历当前节点的子节点了
if (depth >= 4)
return;
// 遍历当前节点的子节点
for (int i : fa[u])
{
// 如果当前节点走过
if (vis[i])
{
check = false;
return;
}
// 将当前节点标记为走过
vis[i] = true;
// 继续遍历当前节点下的节点 且深度+1
dfs(i, depth + 1);
}
}
public static void main(String[] args) throws IOException
{
for (int i = 0; i <= N; i++)
fa[i] = new ArrayList<Integer>();
int n = sc.nextInt();
for (int i = 1; i <= n; i++)
{
int id = sc.nextInt();
sex[id] = sc.next();
int father = sc.nextInt(), mother = sc.nextInt();
if (father != -1)
{
sex[father] = "M";
fa[id].add(father);
}
if (mother != -1)
{
sex[mother] = "F";
fa[id].add(mother);
}
}
int k = sc.nextInt();
while (k-- > 0)
{
int a = sc.nextInt(), b = sc.nextInt();
// 两个人同性
if (sex[a].equals(sex[b]))
{
out.println("Never Mind");
continue;
}
Arrays.fill(vis, false);
check = true;
dfs(a, 0);
dfs(b, 0);
out.println(check ? "Yes" : "No");
}
out.flush();
out.close();
}
static Scanner sc = new Scanner(System.in);
static PrintWriter out = new PrintWriter(System.out);
}
c++
#include <iostream>
#include <string.h>
#include <unordered_map>
#include <vector>
using namespace std;
const int N = 1e5;
unordered_map<int, string> sex;
vector<int> fa[N + 10];
bool vis[N + 10];
bool check;
void dfs(int u, int depth)
{
if(depth >= 4)
return;
for(int i : fa[u])
{
if(vis[i])
{
check = false;
return;
}
vis[i] = true;
dfs(i, depth + 1);
}
}
int main()
{
int n; cin >> n;
for (int i = 1; i <= n; i ++)
{
int id, father, mother; cin >> id >> sex[id] >> father >> mother;
if(father != -1)
{
fa[id].push_back(father);
sex[father] = 'M';
}
if(mother != -1)
{
fa[id].push_back(mother);
sex[mother] = 'F';
}
}
int k; cin >> k;
while(k -- > 0)
{
int a, b; cin >> a >> b;
if(sex[a] == sex[b])
{
cout << "Never Mind" << "\n";
continue;
}
memset(vis, false, sizeof(vis));
check = true;
dfs(a, 0); dfs(b, 0);
cout << (check ? "Yes" : "No") << "\n";
}
return 0;
}