标签:har else rcm return %s img end 图片 strcpy
解题思路:采用结构体来存储家谱
其中需要注意的是祖先和后代的判断
#include <stdio.h> #include <string.h> typedef struct { char s[71]; int space; int parent; } Genealogy; int getparent(Genealogy gene[],int t,int cnt) {//从后向前查找,找到第一个空格相差2个的下标即为双亲下标 int i; for(i=t-1; i>=0; i--) { if(cnt-gene[i].space==2) { return i; } } } int getPos(Genealogy gene[],int t,char str[]) {//查询所在gene结构体数组中的位置下标 int i; for(i=0; i<t; i++) { if(!strcmp(gene[i].s,str)) return i; } } int JudgeDe(Genealogy gene[],int t,int pos1,int pos2) {//判断是否存在祖先关系,若判断是否存在后代关系,则只要将pos1和pos2的位置对调即可 int i=pos1; while(i&&gene[i].parent!=pos2) { i=gene[i].parent; } if(gene[i].parent==pos2) return 1; return 0; } int main() { int n,m; scanf("%d %d\n",&n,&m); Genealogy gene[n]; int i,t=0; char c[71]; char str[71]; for(i=0; i<n; i++) { gets(c); int j=0,k=0; int cnt=0; while(c[j]!=‘\0‘) { if(c[j]==‘ ‘) { cnt++; } else { str[k++]=c[j]; } j++; } str[k]=‘\0‘; strcpy(gene[t].s,str); gene[t].space=cnt; if(!t) gene[t].parent=-1; else gene[t].parent=getparent(gene,t,cnt); t++; } for(i=0; i<m; i++) { char na[71],nb[71],c1[3],c2[4],c3[11],c4[3]; scanf("%s%s%s%s%s%s",na,c1,c2,c3,c4,nb); int pos1=getPos(gene,t,na); int pos2=getPos(gene,t,nb); int flag=0; if(!strcmp(c3,"child")) { if(gene[pos1].parent==pos2) flag=1; } else if(!strcmp(c3,"parent")) { if(gene[pos2].parent==pos1) flag=1; } else if(!strcmp(c3,"sibling")) { if(gene[pos1].parent==gene[pos2].parent) flag=1; } else if(!strcmp(c3,"descendant")) { flag=JudgeDe(gene,t,pos1,pos2); } else if(!strcmp(c3,"ancestor")) { flag=JudgeDe(gene,t,pos2,pos1); } if(flag) printf("True\n"); else printf("False\n"); } return 0; }
标签:har else rcm return %s img end 图片 strcpy
原文地址:https://www.cnblogs.com/snzhong/p/12589483.html