POJ 1094 Sorting It All Out 拓扑排序

题目大意:

给出若干不等式,判断这些不等式是否有冲突,没有冲突的话是否能够成唯一拓扑序列.

解答:

采用拓扑排序即可,拓扑排序可判断图中是否有环.

代码:

#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;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值