AcWIng343 排序(传递闭包)

使用floyd求取传递闭包,每次都进行判断

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=27;
int g[N][N];
bool st[N];
int n,m;
int d[N][N];
void floyd(){
    int i,j,k;
    for(k=1;k<=n;k++){
        for(i=1;i<=n;i++){
            for(j=1;j<=n;j++)
                d[i][j]|=(d[i][k]&&d[k][j]);
        }
    }
}
int check(){
    int i,j;
    for(i=1;i<=n;i++)
        if(d[i][i])
        return 1;
    for(i=1;i<=n;i++){
        for(j=1;j<i;j++){
            if(!d[i][j]&&!d[j][i])
                return 0;
        }
    }
    return 2;
}
char get_min(){
    int i,j;
    for(i=1;i<=n;i++){
        if(!st[i]){
            int flag=0;
            for(j=1;j<=n;j++){
                if(!st[j]&&d[j][i]){
                    flag=1;
                    break;
                }
            }
            if(!flag){
                st[i]=1;
                return 'A'+i-1;
            }
        }
    }
}
int main(){
    int i;
    while(cin>>n>>m){
        if(!n&&!m)
            break;
        memset(d,0,sizeof d);
        int type=0;
        char s[5];
        int t;
        for(i=1;i<=m;i++){
            scanf("%s",s);
            if(!type){
                int tmp1=s[0]-'A'+1,tmp2=s[2]-'A'+1;
                d[tmp1][tmp2]=1;
                floyd();
                type=check();
                if(type)
                    t=i;
            }
        }
        if(!type){
            cout<<"Sorted sequence cannot be determined."<<endl;
        }
        else if(type==1){
            printf("Inconsistency found after %d relations.\n", t);
        }
        else{
            memset(st, 0, sizeof st);
            printf("Sorted sequence determined after %d relations: ", t);
            for (int i = 1; i <= n; i ++ ) printf("%c", get_min());
            printf(".\n");
        }
    }
}
View Code

 

posted @ 2020-05-05 10:12  朝暮不思  阅读(174)  评论(0编辑  收藏  举报