POJ2021

来源:互联网 发布:戴维斯双杀 知乎 编辑:程序博客网 时间:2024/05/17 02:52

摘要:终于3级了。哈哈,BFS

#include <iostream>
#include <map>
#include <string>
#include <queue>
#include <utility>
#include <algorithm>
using namespace std;
 
typedef pair<string, int> person;

bool compareAge(person d1, person d2)
{
    if(d1.second == d2.second){
        return d1.first < d2.first;
    }
   
    return d1.second > d2.second;
}

map<string, map<string, int> > chain;
queue<person> q;
vector<person> vec;


void BFS()
{
    map<string, int> child = chain["Ted"];
    for(map<string, int>::iterator iter=child.begin(); iter!=child.end(); iter++){
        q.push(make_pair(iter->first, 100-iter->second));
    }
   
    while(true){
        if( q.empty() ){
            break;
        }       
        person current = q.front();
        q.pop();
        vec.push_back(current);
        if(chain.find(current.first) == chain.end()){
            continue;
        }
        child = chain[current.first];
        for(map<string, int>::iterator iter=child.begin(); iter!=child.end(); iter++){
            q.push(make_pair(iter->first, current.second - iter->second));
        }
    }
    sort(vec.begin(), vec.end(), compareAge);
}

int main()
{
    int n;
    cin >> n;
    int index = 1;
    while( n > 0 ){
        int dec_num;
        cin >> dec_num;
        while( !q.empty() ){
            q.pop();
        }   
        chain.clear();
        vec.clear();
       
        while( dec_num > 0 ){
            string father;
            string child;
            int f_age;
            cin >> father >> child;
            cin >> f_age;
            chain[father][child] = f_age;
            dec_num--;
        }
        BFS();
        cout << "DATASET " << index++ << endl;
        for(vector<person>::iterator iter=vec.begin(); iter!=vec.end(); iter++){
            cout << iter->first << " " << iter->second << endl;
        }   

        n--;
    }

    return 0;
}