C++#include<bits/stdc++.h>
using namespace std;
const int maxn=1e2+10;
int n,m,ans,cnt;
int d[maxn],_d[maxn];
char _topo[maxn];
vector<int>e[maxn];
map<char,int>mp;
map<int,char>char_mp;
bool flag=1;
int ans1;
void topo(int id)
{
ans=0;
queue<int>q;
for(int i=1;i<=cnt;i++)
{
_d[i]=d[i];
if(_d[i]==0)
{
q.push(i);
}
}
// int sum=0;
while(!q.empty())
{
int u=q.front();
q.pop();
ans++;
if(flag)ans1=id,_topo[ans]=char_mp[u];
for(auto v:e[u])
{
_d[v]--;
if(_d[v]==0)
{
// sum++;
q.push(v);
}
}
}
if(ans==n)
{
flag=0;
// cout<<"Sorted sequence determined after "<<id<<" relations: ";
// for(int i=1;i<=ans;i++)
// {
// cout<<_topo[i];
// }
// cout<<".";
// exit(0);
}
if(flag&&ans<cnt)
{
cout<<"Inconsistency found after "<<id<<" relations.";
exit(0);
}
// if(id==m&&ans<n)
// {
// cout<<"Sorted sequence cannot be determined.";
// exit(0);
// }
}
int main()
{
cin>>n>>m;
for(int i=1;i<=m;i++)
{
char s1,s2,x;
cin>>s1>>x>>s2;
// if(s1==s2)
// {
// cout<<"Inconsistency found after "<<i<<" relations.";
// return 0;
// }
if(!mp[s1])mp[s1]=++cnt,char_mp[cnt]=s1;
if(!mp[s2])mp[s2]=++cnt,char_mp[cnt]=s2;
int _s1=mp[s1],_s2=mp[s2];
d[_s2]++;
e[_s1].push_back(_s2);
topo(i);
}
if(flag==0)
{
cout<<"Sorted sequence determined after "<<ans1<<" relations: ";
for(int i=1;i<=n;i++)
{
cout<<_topo[i];
}
cout<<".";
return 0;
}
else
{
cout<<"Sorted sequence cannot be determined.";;
return 0;
}
return 0;
}