40pts,求条
  • 板块P1347 排序
  • 楼主lover520
  • 当前回复3
  • 已保存回复3
  • 发布时间2025/8/31 17:27
  • 上次更新2025/9/1 00:07:47
查看原帖
40pts,求条
993284
lover520楼主2025/8/31 17:27
#include <bits/stdc++.h>
using namespace std;
const int N=1e5+10;
int head[N],Next[N],ver[N],tot;
int n,m,in[N],in2[N];
string ans;
void build(int x,int y){
    tot++;
    ver[tot]=y;
    Next[tot]=head[x];
    head[x]=tot;
}
int topo(){
    queue <int> q;
    memcpy(in2,in,sizeof(in));
    ans.clear();
    for(int i=1;i<=n;i++){
        if(in2[i]==0){
            q.push(i);
        }
    }
    if(q.size()>1){
        return 1;
    }
    if(q.empty()){
        return 2;
    }
    while(!q.empty()){
        int x=q.front();
        q.pop();
        ans+=char(x+'A'-1);
        for(int i=head[x];i!=-1;i=Next[i]){
            int y=ver[i];
            in2[y]--;
            if(in2[y]==0){
                q.push(y);
                if(q.size()>1){
                    return 1;
                }
            }
        }
    }
    if(ans.size()!=n)return 2;
    return 0;
}
int main(){
    tot=-1;
    memset(head,-1,sizeof(head));
    cin>>n>>m;
    for(int i=1;i<=m;i++){
        char x,p,y; 
        cin>>x>>p>>y;
        int a=x-'A'+1;
        int b=y-'A'+1;
        int f=0;
        if(a==b){
            cout<<"Inconsistency found after "<<i<<" relations."<<endl;
            return 0;
        }
        for(int j=head[a];j!=-1;j=Next[j]){
            if(ver[j]==b){
                f=1;
                break;
            }
        }
        
        if(f==0){
            build(a,b);
            in[b]++;
        }
        int res=topo();
        if(res==2){
            cout<<"Inconsistency found after "<<i<<" relations."<<endl;
            return 0;
        }
        if(res==0){
            cout<<"Sorted sequence determined after "<<i<<" relations: "<<ans<<"."<<endl;
            return 0;
        }
    }
    cout<<"Sorted sequence cannot be determined."<<endl;
    return 0;
}
2025/8/31 17:27
加载中...