#include<iostream>
#include<algorithm>
#include<fstream>
using namespace std;
static const int MAX = 100;
struct info
{ char name[32]; int age; };
struct info descent[MAX];
bool cmp(info &a, info &b) /* 降序排列 */
{
if (a.age > b.age) return true;
if (a.age == b.age && strcmp(a.name, b.name) < 0) return true;
return false;
}
//#define DEBUG
/* 260K 0MS */
int main()
{
#ifdef DEBUG
fstream cin("G:\\book\\algorithms\\acm\\Debug\\dat.txt");
#endif
char father[MAX][32];
char son[MAX][32];
int year[MAX];
int t, num = 0;
cin >> t;
while (t-- > 0)
{
int n; cin >> n;
int i;
for (i = 0; i < n; i++)
{
//scanf("%s%s%d",father[i], son[i], &year[i]);
cin >> father[i] >> son[i] >> year[i];
}
int j, k = 1, cur = 0;
descent[0].age = 100; strcpy(descent[0].name, "Ted");
for (i = 0; i < n; i++, cur++)
{
if (cur >= k) break;
for (j = 0; j < n; j++)
{
if (!strcmp(descent[cur].name, father[j])) /**/
{
strcpy(descent[k].name, son[j]);
descent[k].age = descent[i].age - year[j];
k++;
}
}
}
sort(descent, descent + k, cmp);
printf("DATASET %d\n", ++num);
for (i = 1; i < k; i++)
printf("%s %d\n", descent[i].name, descent[i].age);
}
return 0;
}
分析题目自后感觉是个BFS的问题,BFS的代码设计需要队列进行辅助。该题的关键在于descent队列的设计。
Ted Bill 25
给出根节点的数据(Ted, 100),要求找到Ted的所有后代及年龄。
数据规模太小了,感觉像一道水题。如果规模更大,需要对Birth Certificate List重新组织成更利于查找的数据结构,比如BST。