POJ 1094 Sorting It All Out(拓扑排序)
http://poj.org/problem?id=1094
题意:给你字母表的前N个大写字母和M个大小关系.其中要你在能判断出全序或矛盾的时候及时输出.或者直到最后也不能出现全序.
分析:
我们只需要对于每一条边(共M条有向边)都调用一次topo排序,看看能否出现结果或者出现矛盾即可.
如果能topo排序就说明没有矛盾,但是可能是全序或者偏序集.如果是全序集,那么topo排序的过程中,入度为0的点始终只会存在1个.
AC代码:
#include<cstdio>
#include<cstring>
#include<queue>
#include<vector>
using namespace std;
const int maxn=26+5;
vector<int> G[maxn];
int in[maxn];
int n,m;
char order[1000][10];
char ans[maxn];
int cnt;//记录ans中当前字母
int topo()
{
cnt=0;
queue<int> Q;
int indegree[maxn]; //错误1,这里要重新用一个入度数组
memcpy(indegree,in,sizeof(in));
bool all_order=true;//全序标记
for(int i=0;i<n;i++)if(indegree[i]==0) Q.push(i); //错误2,忘了入度0才入队列
while(!Q.empty())
{
if(Q.size()>1) all_order=false;//Q中始终只有1个元素才能保证全序
int u=Q.front(); Q.pop();
ans[cnt++]=u+'A';
for(int i=0; i<G[u].size(); i++)
{
int v=G[u][i];
if(--indegree[v]==0) Q.push(v);
}
}
int result = 0;
if(cnt<n) result = -1;//存在环
else if(all_order==true) result=1;//已然全序
return result;
}
int main()
{
while(scanf("%d%d",&n,&m)==2&&n)
{
memset(in,0,sizeof(in));
for(int i=0;i<n;i++) G[i].clear();
for(int i=0;i<m;i++)
scanf("%s",order[i]);
int flag=0,i;
for(i=0;i<m;i++)
{
int u=order[i][0]-'A', v=order[i][2]-'A';
G[u].push_back(v);
in[v]++;
if( (flag=topo())!=0) break;
}
ans[n]=0; //错误,这句没加,这个错误很难找
if(flag==1) printf("Sorted sequence determined after %d relations: %s.\n",i+1,ans);
else if(flag==0) printf("Sorted sequence cannot be determined.\n");
else if(flag==-1) printf("Inconsistency found after %d relations.\n",i+1);
}
return 0;
}
分享到:
相关推荐
北大POJ1094-Sorting It All Out 解题报告+AC代码
NULL 博文链接:https://200830740306.iteye.com/blog/603488
poj 1091 拓扑排序加上foyld_warshall算法实现
DNA Sorting Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 34868 Accepted: 13480 Description One measure of ``unsortedness'' in a sequence is the number of pairs of entries that are ...
poj dna sorting 问题,研究的ac coderrrrrrr
北大POJ1936-All in All 解题报告+AC代码
北大POJ1007-DNA Sorting 解题报告+AC代码
初期: 一.基本算法: (1)枚举. (poj1753,poj2965) ... (4)拓扑排序 (poj1094) (5)二分图的最大匹配 (匈牙利算法) (poj3041,poj3020) (6)最大流的增广路算法(KM算法). (poj1459,poj3436) ......
北大POJ1691-Painting A Board 【拓扑+DFS】 解题报告+AC代码
poj 2409 Let it Bead.md
poj 1308 Is It A Tree_.md
POJ分类POJ分类POJ分类POJ分类POJ分类POJ分类POJ分类POJ分类POJ分类POJ分类POJ分类POJ分类POJ分类POJ分类POJ分类POJ分类POJ分类POJ分类
poj 解题报告poj 解题报告poj 解题报告poj 解题报告poj 解题报告poj 解题报告poj 解题报告poj 解题报告poj 解题报告poj 解题报告poj 解题报告poj 解题报告poj 解题报告poj 解题报告poj 解题报告poj 解题报告poj 解题...
POJ第1861题源码 POJ第1861题源码 POJ第1861题源码
poj分类poj分类poj分类poj分类
北大POJ1159-Palindrome 解题报告+AC代码
poj 3414解题报告poj 3414解题报告poj 3414解题报告poj 3414解题报告
POJ上的一道题,我感觉挺难的。分享给大家,这是利用拓扑排序实现,也算是拓扑排序的一道例题。有助于大家对拓排的理解
poj 1012解题报告poj 1012解题报告poj 1012解题报告poj 1012解题报告
poj 2329解题报告poj 2329解题报告poj 2329解题报告poj 2329解题报告