传递闭包:sorting it all out
作者:互联网
给定n个不等式 判断是否有逻辑错误
floyd传递闭包问题
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
const int N=1010;
int read()
{
int x=0,f=0,c=getchar();
while(c<'0'||c>'9'){if(c=='-')f=1;c=getchar();}
while(c>='0'&&c<='9'){x=x*10+c-'0';c=getchar();}
return f?-x:x;
}
struct Edge
{
int to,next;
}e[N*N];
int head[N],cnt,deg[N];
void add(int a,int b){e[++cnt]=(Edge){b,head[a]};head[a]=cnt;deg[b]++;}
int n,m;
bool d[N][N];
queue<int> q;
int ret;
void clean()
{
for(int i=1;i<=n;i++)
{
head[i]=deg[i]=0;
for(int j=1;j<=n;j++) d[i][j]=0;
}
ret=cnt=0;
while(q.size()) q.pop();
}
int floyd()
{
for(int k=1;k<=n;k++)
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
d[i][j] |= d[i][k]&d[k][j];
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
if( d[i][j] &&d[j][i]) return -1;
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
{
if(i==j) continue;
else if(!d[i][j]&&!d[j][i]) return 0;
}
return 1;
}
void topo()
{
for(int i=1;i<=n;i++)
if(!deg[i]) q.push(i);
while(q.size())
{
int x=q.front(); q.pop();
putchar(x+'A'-1);
for(int i=head[x];i;i=e[i].next)
{
int y=e[i].to;
deg[y]--;
if(!deg[y]) q.push(y);
}
}
puts(".");
}
int main()
{
loop:
while( ( n=read() )&& ( m=read() ) )
{
clean();
for(int i=1;i<=m;i++)
{
int x=getchar()-'A'+1; bool opt=getchar()=='>'; int y=getchar()-'A'+1;
getchar();
if(opt) d[x][y]=1,add(y,x);
else d[y][x]=1,add(x,y);
ret=floyd();
if(ret==1)
{
printf("Sorted sequence determined after %d relations: ", i);
topo();
goto loop;
}
if(ret==-1)
{
printf("Inconsistency found after %d relations.\n",i);
goto loop;
}
}
if(ret==0) puts("Sorted sequence cannot be determined.");
}
return 0;
}
这个题目的易错点在于:
1 矛盾的优先级高于推不出来结果 因此要优先判断
2. 关于需不需要判断i和j相等的问题 矛盾和推不出结果是两种情况
3. 传递闭包的关系输出: 拓扑排序
标签:闭包,sorting,sequence,int,ret,include,out,getchar 来源: https://www.cnblogs.com/juruoHBr/p/15779397.html