POJ1094

/**/
#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdio>
#include <string>
#include <vector>
#include <cctype>
#include <queue>
#include <stack>
#include <cmath>
#include <map>
#include <set>
#define mm(i,v) memset(i,v,sizeof i);
using namespace std;

typedef long long ll;
typedef unsigned long long ull;

const ll INF=99999999999999;
const int inf=999999999;
const int maxn=26+5;
vector<int> e[maxn];
int n,m;
int in[maxn],temp[maxn];
int u,v;
queue<int> q;
char a[4],c[maxn];
int ans,cnt;

int Toposort(){
	while(!q.empty())
		q.pop();
	for(int i=0;i<n;i++)
		if(!in[i])
			q.push(i);
	bool unsure=false;
	cnt=0;
	while(!q.empty()){
		// cout<<1<<endl;
		if(q.size()>1)
			unsure=true;
		int qq=q.front();
		c[cnt++]=qq+'A';
		q.pop();
		for(int i=0;i<e[qq].size();i++){
			in[e[qq][i]]--;
			if(in[e[qq][i]]==0)
				q.push(e[qq][i]);
		}
	}
	if(cnt<n)
		return 2;
	if(unsure)
		return 3;
	return 1;
}

bool check(int x,int y){
	for(int i=0;i<e[x].size();i++)
		if(e[x][i]==y)
			return true;
	return false;
}

int main()
{
	//freopen("in.txt", "r", stdin);
	//freopen("out.txt", "w", stdout);
	// ios::sync_with_stdio(false);
	// cin.tie(0);

	while(scanf("%d%d", &n, &m) != EOF && (m || n)){
		// cout<<n<<m<<endl;
		bool f=false;
		int step,flag;
		for(int i=0;i<maxn;i++)
			e[i].clear();
		mm(in,0);
		for(int i=1;i<=m;i++){
			scanf("%s",a);
			// cout<<a<<_<<b<<endl;
			if(f)
				continue;
			u=a[0]-'A';
			v=a[2]-'A';
			if(!check(u,v)){
				e[u].push_back(v);
				in[v]++;
			}
			memcpy(temp,in,sizeof in);
            flag=Toposort();
			memcpy(in,temp,sizeof temp);
			if(flag!=3){
				f=true;
				step=i;
			}
		}
		if (flag == 1)
        {
            c[cnt] = '\0';
            printf("Sorted sequence determined after %d relations: %s.\n", step, c); 
        }
        else if (flag == 2)
            printf("Inconsistency found after %d relations.\n", step);
        else
            printf("Sorted sequence cannot be determined.\n");
	}

	return 0;
}

/*
    summary:处理字符串时谨慎用cin,cout!
*/

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值