90分,WA #5
  • 板块P1347 排序
  • 楼主New_hope
  • 当前回复6
  • 已保存回复6
  • 发布时间2023/7/27 10:37
  • 上次更新2023/11/3 07:26:22
查看原帖
90分,WA #5
416242
New_hope楼主2023/7/27 10:37
#include<bits/stdc++.h>
using namespace std;

queue<int> q;
vector<int> g[30];

bool vis[30],certain;
int ind[30],temp[30],topo[30];
int n,m;

bool toposort(int cnt)
{
    memset(temp,0,sizeof(temp));
    memset(topo,0,sizeof(topo));
    while(!q.empty()) q.pop();
    
    certain = 1;
    for(int i = 0; i < n; i ++) temp[i] = ind[i];
    // for(int i = 0; i < n; i ++) cout << temp[i] << " ";
    for(int i = 0; i < n; i ++){
        if(!temp[i]){
            // cout << char(i+'A') << " ";
            q.push(i);
        }
    }
    // cout << endl;

    int depth = 0;
    while(!q.empty())
    {
        int t = 0;
        int fr = q.front(); q.pop();
        depth ++;
        topo[depth] = fr;
        // cout << "head:" << char(fr+'A') << "->";
        for(int i = 0; i < (int)g[fr].size(); i ++){
            int v = g[fr][i];
            // cout << char(v+'A') << " ";
            if(--temp[v] == 0){
                t ++;
                q.push(v);
            }
        } 
        if(t > 1) certain = 0;
        // cout << endl;
    }
    // cout << endl << k << " " << depth << endl;
    // for(int i = 1; i <= depth; i ++) cout << (topo[i]+'A') << " ";
    // cout << "k=" << k << " " << " num:" << cnt << endl;
    if(depth < cnt) return 0;
    else return 1;
}
int main()
{
    int cnt = 0;
    cin >> n >> m;
    for(int i = 1; i <= m; i ++){
        string s;
        cin >> s;
        char a = s[0], b = s[2];
        int ta = a-'A', tb = b-'A';
        g[ta].push_back(tb);
        ind[tb] ++;
        if(!vis[ta]){
            vis[ta] = 1;
            cnt ++;
        }
        if(!vis[tb]){
            vis[tb] = 1;
            cnt ++;
        }
        if(!toposort(cnt)){
            cout << "Inconsistency found after " << i << " relations.";
			exit(0);
        }
        else{
            if(cnt == n && certain){
                cout << "Sorted sequence determined after " << i << " relations: ";
				for (int i = 1; i <= n; ++i) cout << (char)(topo[i] + 'A');
				cout << '.';
				exit(0);
            }
        }
    }
    cout << "Sorted sequence cannot be determined.";
    return 0;
}
2023/7/27 10:37
加载中...