【圖論】拓撲排序+優先佇列

CN_swords發表於2017-07-01

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<stack>
#include<queue>
#include<deque>
#include<vector>
#include<map>
#include<algorithm>
using namespace std;
typedef long long LL;
//#pragma comment(linker, "/STACK:102400000,102400000")

const double PI = acos(-1.0);
const double eps = 1e-6;
const int INF=0x3f3f3f3f;
const int N=100010;
const LL mod = 1e9+7;

struct asd
{
    string name;
    int in;
    int id;
} a[N];
struct cmp
{
    bool operator()(asd &a,asd &b)
    {
        if(a.in != b.in)
            return a.in > b.in;
        return a.name > b.name;
    }
};
map<string,int> mp;
vector<int> ma[N];
int idx;
int creat(string s)
{
    if(mp[s]==0)
    {
        mp[s] = idx;
        a[idx].id = idx;
        a[idx++].name = s;
    }
    return mp[s];
}
int n;
int main()
{
    string s;
    while(cin >> n)
    {
        priority_queue<asd,vector<asd>,cmp> Q;
        idx = 0;
        mp.clear();
        for(int i = 0; i < n; i++)
        {
            cin >> s;
            string name = "";
            for(int i = 0; i < s.length(); i++)
            {
                int from,to;
                if(s[i] == '(')
                {
                    from = creat(name);
                    name = "";
                }
                else if(s[i] == ')' || s[i] == ',')
                {
                    if(name != "NULL")
                    {
                        to = creat(name);
                        a[to].in++;
                        ma[from].push_back(to);
                    }
                    name = "";
                }
                else
                    name += s[i];
            }
        }
        //cout << idx << endl;
        for(int j = 0; j < idx; j++)
        {
            if(a[j].in == 0)
                Q.push(a[j]);
        }
        int frist = 1;
        while(!Q.empty())
        {
            asd temp = Q.top();
            Q.pop();
            if(frist){
                cout << temp.name;
                frist = 0;
            }
            else
                cout << " " << temp.name;
            for(int i = 0; i < ma[temp.id].size(); i++)
            {
                a[ma[temp.id][i]].in--;
                if(a[ma[temp.id][i]].in == 0)
                    Q.push(a[ma[temp.id][i]]);
            }
        }
        cout << endl;
    }
    return 0;
}


相關文章