题意:
给m个三元组(str1,str2,age)表示孩子str2比父亲str1大age岁,要将所有人按年龄从大往小输出,如有年龄相同的情况按字典序从大到小输出。
分析:
用map将每个人与一个id对应,求出年龄后不需要在每个人的信息上直接排序,可以在id上间接排序。
代码:
//poj 2021
//sep9
#include <iostream>
#include <map>
#include <string>
#include <algorithm>
using namespace std;
map<string,int> m;
int age[256],p[256],small[256],ans[256];
string name[256];int cmp(int x,int y)
{if(age[x]==age[y])return name[x]<name[y];return age[x]>age[y];
}int getAge(int son)
{if(name[son]=="Ted")return 100;else if(age[son]!=-1)return age[son];else{int pAge=getAge(p[son]);return age[son]=pAge-small[son];}
}int main()
{int cases,t=0;scanf("%d",&cases);while(cases--){int i,n,deta,ids;scanf("%d",&n); m.clear();ids=0;memset(age,-1,sizeof(age));memset(p,-1,sizeof(p));for(i=1;i<=n;++i){string parent,child;cin>>parent>>child;int x;cin>>x;if(m[parent]==0)m[parent]=++ids;if(m[child]==0)m[child]=++ids;int a=m[parent];int b=m[child];p[b]=a; small[b]=x;}map<string,int>::iterator iter;for(iter=m.begin();iter!=m.end();++iter)name[iter->second]=iter->first; for(i=1;i<=ids;++i)if(age[i]==-1)age[i]=getAge(i);for(i=1;i<=ids;++i)ans[i]=i;sort(ans+1,ans+1+ids,cmp);printf("DATASET %d\n",++t);for(i=1;i<=ids;++i)if(name[ans[i]]!="Ted")cout<<name[ans[i]]<<" "<<age[ans[i]]<<endl; } return 0;
}