题目大意:
给出若干不等式,判断这些不等式是否有冲突,没有冲突的话是否能够成唯一拓扑序列.
解答:
采用拓扑排序即可,拓扑排序可判断图中是否有环.
代码:
#include<iostream> #include<cstring> #include<vector> #include<string> using namespace std; class SortingItAllOut { int count[26],temp[26],n,relations,ans;//count为各点入度,同时为拓扑排序所用栈,temp为其备份 char s[3],seq[27]; vector <vector <char> > v;//邻接表存图 void initial(); void topo(); public: void work(int,int); }; void SortingItAllOut::work(int a,int b) { if(a==0&&b==0)return; n=a;relations=b; initial(); int i; bool f=false; for(i=1;i<=relations;i++) { cin>>s; if(f)continue; count[s[2]-'A']++; v[s[0]-'A'].push_back(s[2]); ans=0; topo(); if(ans==1) { cout<<"Sorted sequence determined after "<<i<<" relations: "<<seq<<"."<<endl; f=true; } if(ans==-1) { cout<<"Inconsistency found after "<<i<<" relations."<<endl; f=true; } } if(!f)cout<<"Sorted sequence cannot be determined."<<endl; } void SortingItAllOut::initial() { v.clear();v.resize(n); memset(count,0,sizeof(count)); memset(seq,'\0',sizeof(seq)); } void SortingItAllOut::topo() { int i,j,num=0,top=-1,_top; for(i=0;i<n;i++) { temp[i]=count[i]; if(temp[i]==0){temp[i]=top;top=i;num++;} } for(i=0;i<n;i++) { if(top==-1){ans=-1;return;}//图中有环 if(num==1)num=0; seq[i]=top+'A'; _top=top; top=temp[top];//出栈 for(j=0;j<v[_top].size();j++) { if(--temp[v[_top][j]-'A']==0){num++;temp[v[_top][j]-'A']=top;top=v[_top][j]-'A';}//入栈 } } if(num>1)ans=0;//拓扑序列不唯一 else ans=1; } SortingItAllOut SIAO; int main() { int a,b; while(cin>>a>>b) SIAO.work(a,b); return 0; }