按照亲子关系建立一棵树,边的权值表示父子年龄差值,点的权值表示个人的年龄
然后遍历树输出
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <set>
#include <vector>
#include <algorithm>
#include <map>
using namespace std;
#define maxn 110
int t, n;
map<string, int> id;
struct Edge{
string ch;
int dif;
Edge(string c, int d):ch(c), dif(d){}
};
vector<Edge> G[maxn];
int getId(string s){
int i;
if(id.find(s) == id.end()){
i = id.size();
id.insert(make_pair(s, i));
}
else i = id[s];
return i;
}
struct node{
string name;
int age;
node(string n, int a):name(n), age(a){}
bool operator<(const node& t)const{
return (age==t.age&&name<t.name) || age>t.age;
}
};
vector<node> list;
void dfs(int root, int r_age){
for(int i=0; i<G[root].size(); i++){
string name = G[root][i].ch;
int age = r_age-G[root][i].dif;
list.push_back(node(name, age));
dfs(id[G[root][i].ch], age);
}
}
void init(){
id.clear();
for(int i=0; i<maxn; i++) G[i].clear();
list.clear();
}
int main(){
// freopen("a.txt", "r", stdin);
cin>>t;
for(int kase=1; kase<=t; kase++){
init();
printf("DATASET %d\n", kase);
cin>>n;
string fa, ch;
int dif;
for(int i=0; i<n; i++)
{
cin>>fa>>ch>>dif;
int fi = getId(fa);
int ci = getId(ch);
G[fi].push_back( Edge(ch, dif) );
}
int root = getId("Ted");
dfs(root, 100);
sort(list.begin(), list.end());
for(int i=0; i<list.size(); i++){
cout<<list[i].name<<" "<<list[i].age<<endl;
}
}
return 0;
}