今天舍友回来,等会回去啊了他怎么样。
题意:
对于前n个大写字母,给出他们之间m个小于关系,要求确定他们是否存在矛盾,或者存在唯一的拓扑序,或者无法确定排序,当已输入的关系可以得出三种结论中的一种时,就得出结论,即使和后面的矛盾。
Input
Input consists of multiple problem instances. Each instance starts with a line containing two positive integers n and m. the first value indicated the number of objects to sort, where 2 <= n <= 26. The objects to be sorted will be the first n characters of the uppercase alphabet. The second value m indicates the number of relations of the form A < B which will be given in this problem instance. Next will be m lines, each containing one such relation consisting of three characters: an uppercase letter, the character "<" and a second uppercase letter. No letter will be outside the range of the first n letters of the alphabet. Values of n = m = 0 indicate end of input.
Output
For each problem instance, output consists of one line. This line should be one of the following three:Sorted sequence determined after xxx relations: yyy...y.
Sorted sequence cannot be determined.
Inconsistency found after xxx relations.
where xxx is the number of relations processed at the time either a sorted sequence is determined or an inconsistency is found, whichever comes first, and yyy...y is the sorted, ascending sequence.
这题一看就知道是拓扑排序,但他还要确定是否是唯一的排序,然后我个逗比就觉得不能用拓扑标准过程来了,先自己写了个拓扑排序,中间夹杂了很多操作,一直TLE,做了组大数据把操作数输出来一看,10^10以上哦凑。。。剪了剪枝还是10^9,然后就按拓扑标程写,又为了确定排序是否唯一加了一些东西,结果WA了。。想明白了怎么回事以后,突然想到,只要跑一个拓扑排序,再按照得出的拓扑序看一下是否每两个相邻的元素都存在边就行了。。。。。。。。。。
所以说,no zuo no die 还是自己太弱。
代码如下:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<string>
using namespace std;
#define mxn 30
int n,m;
bool mapp[mxn][mxn];
int suc,fail;
int flag[mxn],cnt;
char ans[mxn];
void init(){
ans[n]=0;
suc=fail=-1;
memset(mapp,false,sizeof(mapp));
}
bool dfs(int now){
flag[now]=-1;
for(int i=0;i<n;++i) if(mapp[now][i])
if(flag[i]==-1||flag[i]==0&&!dfs(i))
return false;
ans[--cnt]=now+'A';
flag[now]=1;
return true;
}
bool toposort(){
memset(flag,0,sizeof(flag));
cnt=n;
for(int i=0;i<n;++i) if(!flag[i])
if(!dfs(i)) return false;
return true;
}
bool check(){
for(int i=0;i<n-1;++i)
if(!mapp[ans[i]-'A'][ans[i+1]-'A'])
return false;
return true;
}
int main(){
while(scanf("%d%d",&n,&m)!=EOF&&n&&m){
init();
for(int i=0;i<m;++i){
char tem[5];
int u,v;
scanf("%s",tem);
u=tem[0]-'A';
v=tem[2]-'A';
if(!mapp[u][v]&&suc==-1&&fail==-1){
mapp[u][v]=true;
if(!toposort()) fail=i+1;
else if(check()) suc=i+1;
}
}
if(fail!=-1) printf("Inconsistency found after %d relations.\n",fail);
else if(suc!=-1) printf("Sorted sequence determined after %d relations: %s.\n",suc,ans);
else puts("Sorted sequence cannot be determined.");
}
return 0;
}