跳到正文

题解

题解:P10124 [USACO18OPEN] Family Tree B

duancaiwen约 3 分钟
原文
文章信息与版本

文章信息

发布
2024年7月26日
收录
2026年6月25日
更新
2026年10月28日
篇幅
约 3 分钟
获赞
1
题目
P10124

版本

  1. v1当前

知识点:模拟

思路:

首先,设两只奶牛为 A,BA,B 。

因为族谱是一棵树,所以除非 AA 和 BB 之间没有关系,否则可以确定,AA 的 nn 辈祖先是 BB 的 mm 辈祖先。如果 AA 是 BB 的祖先,那么 n=0n = 0 。

我们求的是辈分最小的祖先,所以这不就是最小公共祖先?

由于数据范围小,时间复杂度低,可以直接暴力求。

求出 n,mn,m 之后,就好办了,直接判断:

如果 n=0n=0 ,AA 是 BB 的祖先。

如果 m=0m=0 ,BB 是 AA 的祖先。

如果 n=1n=1 且 m=1m=1 ,AA 和 BB 是姐妹。

如果 n=1n=1 且 m>1m>1 ,AA 是 BB 的姨母。

如果 n>1n>1 且 m=1m=1 ,BB 是 AA 的姨母。

如果 n>1n>1 且 m>1m>1 ,AA 和 BB 是表姐妹。

没有查找到关系,那么这两头奶牛就是没有关系。 最后,纯模拟就可以了。

code

C++
#include<bits/stdc++.h>//万能头
using namespace std;
int n,k1=114514,k2=1919810,q=0,w=0;
string a,b,s1[101],s2[101],s3[101],s4[101];
void f(string s){
	s3[q]=s;
	q++;
	for(int i=1;i<=n;i++){
		if(s2[i]==s)f(s1[i]);
	}
}
void sc2(string s){
	s4[w]=s;
	w++;
	for(int i=1;i<=n;i++){
		if(s2[i]==s)sc2(s1[i]);
	}
}
void init(){//输入
	cin>>n>>a>>b;
	for(int i=1;i<=n;i++){
		cin>>s1[i]>>s2[i];
	}
	f(a);
	sc2(b);
}
void now(){
	for(int i=0;i<q;i++){
		for(int j=0;j<w;j++){
			if(s3[i]==s4[j]){
				k1=i;
				k2=j;
				return;
			}
		}
	}
}
int main(){
	init();//输入
	now();
	if((k1==1)&&(k2==1))cout<<"SIBLINGS";
	else if(k1==0){
		cout<<a<<" is the ";
		while(k2>=3){
			cout<<"great-";
			k2--;
		}
		if(k2==2)cout<<"grand-";
		cout<<"mother of "<<b;
	}
	else if(k2==0){
		cout<<b<<" is the ";
		while(k1>=3){
			cout<<"great-";
			k1--;
		}
		if(k1==2)cout<<"grand-";
		cout<<"mother of "<<a;
	}
	else if(k1==1){
		cout<<a<<" is the ";
		while(k2>=3){
			cout<<"great-";
			k2--;
		}
		cout<<"aunt of "<<b;
	}
	else if(k2==1){
		cout<<b<<" is the ";
		while(k1>=3){
			cout<<"great-";
			k1--;
		}
		cout<<"aunt of "<<a;
	}
	else if(k1==114514)cout<<"NOT RELATED";
	else cout<<"COUSINS";
	return 0;//完美结尾
}
原文