题意:告诉你族谱,然后Q条查询s和t的关系,妈妈输出M,爸爸输出F;
题目地址:http://acm.hust.edu.cn/vjudge/contest/view.action?cid=78233#problem/D
如查询8 2输出 0 FM(0表示8是2的祖辈)
思路:dfs,bfs都行吧,但我不知道该怎么用bfs生成图,最直接的还是dfs;遍历二叉树,看是否在同一棵树中
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <string> 5 #include <sstream> 6 #include <queue> 7 #include <vector> 8 #define repu(i,a,b) for(int i=a;i<b;i++) 9 using namespace std; 10 #define N 100010 11 int vis[N]; 12 int dir[][2] = {{1,0},{-1,0},{0,1},{0,-1}}; 13 int fa[N],ma[N]; 14 char st[N]; 15 int dfs(int s,int l,int e) 16 { 17 if(s == 0) 18 return 0; 19 if(s == e) 20 return 1; 21 st[l] = 'F'; 22 if(dfs(fa[s],l+1,e))///如果是fa,就根据fa找下去 23 return 1; 24 st[l] = 'M'; 25 if(dfs(ma[s],l+1,e)) 26 return 1; 27 return 0; 28 } 29 int main() 30 { 31 int T,n,Q,a,b,c,s,e; 32 scanf("%d",&T); 33 while(T--) 34 { 35 memset(fa,0,sizeof(fa)); 36 memset(ma,0,sizeof(ma)); 37 scanf("%d",&n); 38 repu(i,0,n/2) 39 { 40 scanf("%d%d%d",&a,&b,&c); 41 fa[a] = b; 42 ma[a] = c; 43 } 44 memset(st,0,sizeof(st)); 45 scanf("%d",&Q); 46 while(Q--) 47 { 48 scanf("%d%d",&s,&e); 49 if(dfs(s,0,e)) 50 printf("1 %s ",st); 51 else if(dfs(e,0,s)) 52 printf("0 %s ",st); 53 else 54 printf("Relative "); 55 } 56 } 57 return 0; 58 }