/**/
#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdio>
#include <string>
#include <vector>
#include <cctype>
#include <queue>
#include <stack>
#include <cmath>
#include <map>
#include <set>
#define mm(i,v) memset(i,v,sizeof i);
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const ll INF=99999999999999;
const int inf=999999999;
const int maxn=26+5;
vector<int> e[maxn];
int n,m;
int in[maxn],temp[maxn];
int u,v;
queue<int> q;
char a[4],c[maxn];
int ans,cnt;
int Toposort(){
while(!q.empty())
q.pop();
for(int i=0;i<n;i++)
if(!in[i])
q.push(i);
bool unsure=false;
cnt=0;
while(!q.empty()){
// cout<<1<<endl;
if(q.size()>1)
unsure=true;
int qq=q.front();
c[cnt++]=qq+'A';
q.pop();
for(int i=0;i<e[qq].size();i++){
in[e[qq][i]]--;
if(in[e[qq][i]]==0)
q.push(e[qq][i]);
}
}
if(cnt<n)
return 2;
if(unsure)
return 3;
return 1;
}
bool check(int x,int y){
for(int i=0;i<e[x].size();i++)
if(e[x][i]==y)
return true;
return false;
}
int main()
{
//freopen("in.txt", "r", stdin);
//freopen("out.txt", "w", stdout);
// ios::sync_with_stdio(false);
// cin.tie(0);
while(scanf("%d%d", &n, &m) != EOF && (m || n)){
// cout<<n<<m<<endl;
bool f=false;
int step,flag;
for(int i=0;i<maxn;i++)
e[i].clear();
mm(in,0);
for(int i=1;i<=m;i++){
scanf("%s",a);
// cout<<a<<_<<b<<endl;
if(f)
continue;
u=a[0]-'A';
v=a[2]-'A';
if(!check(u,v)){
e[u].push_back(v);
in[v]++;
}
memcpy(temp,in,sizeof in);
flag=Toposort();
memcpy(in,temp,sizeof temp);
if(flag!=3){
f=true;
step=i;
}
}
if (flag == 1)
{
c[cnt] = '\0';
printf("Sorted sequence determined after %d relations: %s.\n", step, c);
}
else if (flag == 2)
printf("Inconsistency found after %d relations.\n", step);
else
printf("Sorted sequence cannot be determined.\n");
}
return 0;
}
/*
summary:处理字符串时谨慎用cin,cout!
*/
POJ1094
最新推荐文章于 2023-02-26 11:43:52 发布