40分代码求调
  • 板块P1347 排序
  • 楼主__Floze3__
  • 当前回复0
  • 已保存回复0
  • 发布时间2023/9/7 17:52
  • 上次更新2023/11/2 22:27:13
查看原帖
40分代码求调
558833
__Floze3__楼主2023/9/7 17:52
#include <bits/stdc++.h>
using namespace std;

vector<int> g[30];
int n, m, du[30], cnt[30], ans[650];

int topusort(){
    for (int i = 1; i <= n; i++) cnt[i] = 0;
    memset(ans, 0, sizeof(ans));
    int du1[30];
    queue<int> q;
    bool f = false;
    for (int i = 1; i <= n; i++){
        du1[i] = du[i];
        if (!du[i]){
            if (f) return 0;
            q.push(i);
            f = true;
        }
    }
    if (!f) return -1;
    int pos = 0;
    while(!q.empty()){
        int x = q.front();
        q.pop();
        // cout << x << endl;
        // cout << "=====================" << endl;
        cnt[x]++;
        ans[++pos] = x;
        bool kk = false;
        // cout << g[x].size() << endl;
        for (int i = 0; i < g[x].size(); i++){
            du1[g[x][i]]--;
        }
        for (int i = 0; i < g[x].size(); i++){
            if (!du1[g[x][i]]){
                if (cnt[g[x][i]]) return -1;
                if (kk) return 0;
                kk = true;
                // cout << g[x][i] << ' ';
                q.push(g[x][i]);
            }
        }
        // cout << endl;
    }
    if (pos == n) return 1;
    return -1;
}

void print(){
    for (int i = 1; i <= n; i++) cout << (char)(ans[i] + 'A' - 1);
    cout << '.'<< endl;
    return ;
}

int main(){
    cin >> n >> m;
    for (int i = 1; i <= m; i++){
        char x[5];
        cin >> x;
        if (x[0] == x[2]){
            cout << "Inconsistency found after " << i << " relations." << endl;
            return 0;
        }
        g[x[0] - 'A' + 1].push_back(x[2] - 'A' + 1);
        du[x[2] - 'A' + 1]++;
        int flag = topusort();
        if (flag == 1){
            cout << "Sorted sequence determined after " << i << " relations: ";
            print();
            return 0;
        }
        else if (flag == -1){
            cout << "Inconsistency found after " << i << " relations." << endl;
            return 0;
        }
    }
    cout << "Sorted sequence cannot be determined.";
    return 0;
}
2023/9/7 17:52
加载中...