拓扑排序

淺唱寂寞╮ 提交于 2019-11-29 17:09:42
#include <iostream>
#include <algorithm>
#include <cstring>
#include <string>
#include <sstream>
#include <cstdio>
#include <vector>
#include <queue>
using namespace std;

const int MAXN = 10017;
#define pii pair<int, int>

int n, tot;
vector<int> G[MAXN];
vector<pii> task[MAXN];
bool vis[500000];
int deg[500000];
int dict[MAXN][100];

int work(){
    //init
    tot = 0;
    memset(vis, 0, sizeof(vis));
    memset(deg, 0, sizeof(deg));
    memset(dict, 0, sizeof(dict));
    for(int i = 0; i < n; i++)
        task[i].clear();
    //read
    for(int i = 0; i < n; i++){
        string line;
        getline(cin, line);
        stringstream lin(line);
        char ch;
        int num;
        while(lin >> ch >> num){
            if(ch == 'S')
                task[i].push_back(pii(1, num));
            else
                task[i].push_back(pii(0, num));
        }
    }
    //hash to one node
    for(int i = 0; i < n; i++){
        for(int j = 0; j < task[i].size(); j++){
            if(dict[i][j]) continue;
            int type = task[i][j].first;
            int to = task[i][j].second;
            int index = -1;
            for(int k = 0; k < task[to].size(); k++){
                if(task[to][k].second == i && (task[to][k].first ^ type))
                    index = k;
            }
            if(index == -1)
                return 1;
            dict[i][j] = dict[to][index] = ++tot;
        }
    }
    //clear graph
    for(int i = 0; i <= tot; i++)
        G[i].clear();
    //build gragh
    for(int i = 0; i < n; i++){
        for(int j = 0; j < task[i].size() - 1; j++){
            int node = dict[i][j];
            int nxt = dict[i][j+1];
            G[node].push_back(nxt);
            deg[nxt] ++;
        }
    }
    //sort
    queue<int> q;
    for(int i = 1; i <= tot; i++)
        if(deg[i] == 0)
            q.push(i);
    while(!q.empty()){
        int f = q.front();
        q.pop();
        for(auto nxt : G[f]){
            deg[nxt]--;
            if(deg[nxt] == 0)
                q.push(nxt);
        }
    }
    //judge
    for(int i = 1; i <= tot; i++)
        if(deg[i])
            return 1;
    return 0;
}

int main(){
    int t;
    string line;
    getline(cin, line);
    stringstream lin(line);
    lin >> t >> n;
    while(t--)
        cout << work() << endl;

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!