#include <bits/stdc++.h>
using namespace std;
bool g[26][26]={0};
map <char,int> in;
map <char,int> tmp_in;
vector <char> waiting;
char result[26]={0};
int pos=0;
int n,m;
void prtg(){for (int i=0;i<n;i++){for (int j=0;j<n;j++){printf("%d ",g[i][j]);}printf("\n");}printf("\n");}
void prtin(){for (map<char,int>::iterator iter=in.begin();iter!=in.end();iter++)cout<<iter->first<<':'<<iter->second<<endl;}
void prttmpin(){for (map<char,int>::iterator iter=tmp_in.begin();iter!=tmp_in.end();iter++)cout<<iter->first<<':'<<iter->second<<endl;}
int slove()
{
waiting.clear();
//prttmpin();
if (tmp_in.empty()) return 1;
for (map<char,int>::iterator iter=tmp_in.begin();iter!=tmp_in.end();iter++)
if (iter->second==0)
{
waiting.push_back(iter->first);
}
//if (!waiting.empty()) {for (vector <char>::iterator iter=waiting.begin();iter!=waiting.end();iter++) cout<<*iter;cout<<endl;}
if (waiting.empty())
{
return -1;
}
else if (waiting.size()>1) return 0;
else
{
tmp_in.erase(waiting.front());
result[pos++]=waiting.front();
for (int i=0;i<n;i++)
{
if (g[waiting.front()-'A'][i])
tmp_in.at('A'+i)--;
}
return slove();
}
}
int main(void)
{
waiting.clear();
pos=0;
cin>>n>>m;
char c1,c2;
for (int i=0;i<n;i++)
in.insert({'A'+i,0});
for (int i=1;i<=m;i++)
{
//printf("read in relation %d\n",i);
int cnt=0,pos=0;
getchar();
cin>>c1;
getchar();
cin>>c2;
if (c1==c2)
{
printf("Inconsistency found after %d relations.",i);
return 0;
}
if(!g[c1-'A'][c2-'A'])
{
g[c1-'A'][c2-'A']=1;
in.at(c2)++;
}
//prtg();prtin();
tmp_in=in;
switch (slove())
{
case 1:printf("Sorted sequence determined after %d relations: %s.",i,result);return 0;break;
case 0:continue;break;
case -1:printf("Inconsistency found after %d relations.",i);return 0;break;
}
}
printf("Sorted sequence cannot be determined.");
return 0;
}
思路和题解是一样的,三组测试数据也过了,还是好几个WA,求助