poj 2021 Relative Relatives

按照亲子关系建立一棵树,边的权值表示父子年龄差值,点的权值表示个人的年龄

然后遍历树输出

#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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值