文章
454
粉丝
0
获赞
1
访问
10.3k
给若干条「某人的父母是谁」的记录,多次询问两人是否有直系血缘关系,并按 parent / grandparent / great-grandparent(以及反向的 child 系列)输出关系。
用两个父指针 p1[]、p2[] 表示每个人的父母('-' 表示缺失),构建一棵向上的祖先树。
询问 X、Y 时先算 Y 到 X 的祖先深度 d1(X 是 Y 的祖先则 Y→X 向上走),据此输出 parent(d=1)或带若干个 great- 的 grandparent(d≥2,great 个数为 d-2)。
若不是,再反过来算 X 到 Y 的祖先深度,输出对应的 child 系列;两边都不成立输出 -。
时间 O(n·深度) 每组查询,空间 O(人数)。
C:
#include <stdio.h>
#include <string.h>
int p1[128],p2[128];
int depth(int from,int target){
if(from==target)return 0;
int a=p1[from],b=p2[from];
int best=-1;
if(a>=0){int d=depth(a,target);if(d>=0&&(best<0||d+1<best))best=d+1;}
if(b>=0){int d=depth(b,target);if(d>=0&&(best<0||d+1<best))best=d+1;}
return best;}
void pr(int k,const char*leaf){
if(k==1)printf("%s\n",leaf);
else{printf("%s",k==2?"grand":"");}
}
int main(void){int n,m,i;
char s[8];
while(scanf("%d %d",&n,&m)==2){
for(i=0;i<128;i++){p1[i]=-1;p2[i]=-1;}
for(i=0;i<n;i++){scanf("%s",s);
int a=s[0],...
登录后发布评论
暂无评论,来抢沙发