看到一个代码,几乎完美,我都不想改了。。以后当模板
#include <iostream>
#include <string>
#include <vector>
#include <queue>
using namespace std;
int n,m;
vector<int> top;
vector<int> in;
vector< vector<int> > map;
int topsort(){
int i,u;
bool flag=false;
queue<int> q;
vector<int> d(in.begin(),in.end());
for(i=0;i<n;i++)
if(!d[i]) q.push(i);
top.clear();
while(!q.empty()){
if(q.size()!=1) flag=true;
u=q.front();
q.pop();
top.push_back(u);
for(i=0;i<map[u].size();i++)
if(--d[map[u][i]]==0) q.push(map[u][i]);
}
if(top.size()!=n) return 1;
if(flag) return 0;
return 2;
}
int main(){
string str;
int i,j,u,v,ans;
while(cin>>n>>m,n||m){
in.assign(n,0);
map.assign(n,vector<int>());
for(ans=i=0;i<m && !ans;i++){
cin>>str;
u=str[0]-'A',v=str[2]-'A';
if(find(map[u].begin(),map[u].end(),v)==map[u].end())
map[u].push_back(v),in[v]++;
ans=topsort();
}
for(j=i;j<m;j++) cin>>str;
switch(ans){
case 0:cout<<"Sorted sequence cannot be determined."<<endl;break;
case 1:cout<<"Inconsistency found after "<<i<<" relations."<<endl;break;
case 2:{
cout<<"Sorted sequence determined after "<<i<<" relations: ";
for(j=0;j<n;j++) cout<<char('A'+top[j]);
cout<<"."<<endl;
break;
}
}
}
return 0;
}
代码转自:http://www.cppblog.com/mythit/archive/2009/05/19/83406.html
题意原来是,如果到第几个relations 的时候,出了那三种结果里的哪一种,后面的就可以忽略了。。