沃舍尔传递闭包算法_离散数学 传递闭包
大家好,又见面了,我是你们的朋友全栈君。
给定 n 个变量和 m 个不等式。其中 n 小于等于 26,变量分别用前 n 的大写英文字母表示。
不等式之间具有传递性,即若 A>B 且 B>C,则 A>C。
请从前往后遍历每对关系,每次遍历时判断:
如果能够确定全部关系且无矛盾,则结束循环,输出确定的次序; 如果发生矛盾,则结束循环,输出有矛盾; 如果循环结束时没有发生上述两种情况,则输出无定解。 输入格式 输入包含多组测试数据。
每组测试数据,第一行包含两个整数 n 和 m。
接下来 m 行,每行包含一个不等式,不等式全部为小于关系。
当输入一行 0 0 时,表示输入终止。
输出格式 每组数据输出一个占一行的结果。
结果可能为下列三种之一:
如果可以确定两两之间的关系,则输出 “Sorted sequence determined after t relations: yyy…y.”,其中’t’指迭代次数,’yyy…y’是指升序排列的所有变量。 如果有矛盾,则输出: “Inconsistency found after t relations.”,其中’t’指迭代次数。 如果没有矛盾,且不能确定两两之间的关系,则输出 “Sorted sequence cannot be determined.”。 数据范围 2≤n≤26,变量只可能为大写字母 A∼Z。
输入样例1:
4 6
A<B
A<C
B<C
C<D
B<D
A<B
3 2
A<B
B<A
26 1
A<Z
0 0
输出样例1:
Sorted sequence determined after 4 relations: ABCD.
Inconsistency found after 2 relations.
Sorted sequence cannot be determined.
输入样例2:
6 6
A<F
B<D
C<E
F<D
D<E
E<F
0 0
输出样例2:
Inconsistency found after 6 relations.
输入样例3:
5 5
A<B
B<C
C<D
D<E
E<A
0 0
输出样例3:
Sorted sequence determined after 4 relations: ABCDE.
#include<bits/stdc++.h>
using namespace std;
const int N = 26;
int g[N][N];
int n,m;
struct node{
int id,num;
}Node[N];
bool cmp(const node &a,const node &b){
return a.num < b.num;
}
int vis[N];
int check(){
for(int i = 0;i < n;i ++)
if(g[i][i] == 1)return -1;//矛盾
for(int i = 0;i < n;i ++){
for(int j = i + 1;j < n;j ++){
if(!g[i][j] && !g[j][i])return 0;//不能唯一确定
}
}
return 1;//能唯一确定
}
int main(){
int T;
string line[26 * 26];
while(cin>>n>>m,n || m){
int res = 0;
memset(g,0,sizeof g);
for(int i = 0;i < m;i ++){
cin>>line[i];
}
memset(g,0,sizeof g);
for(int i = 0;i < m;i ++){
int a = line[i][0] - 'A',b = line[i][2] - 'A';
if(line[i][1] == '<')swap(a,b),g[a][b] = 1;
else g[a][b] = 1;
for(int i = 0;i < n;i ++)
{
if(g[i][a])g[i][b] = 1;
if(g[b][i])g[a][i] = 1;
for(int j = 0;j < n;j ++){
if(g[i][a] && g[b][j])g[i][j] = 1;
}
}
int flag = check();
if(flag == -1){
printf("Inconsistency found after %d relations.n",i + 1),res = 1;
break;
}
if(flag == 0)continue;
else{
for(int i = 0;i < n;i ++){
Node[i].num = 0;
for(int j = 0;j < n;j ++){
if(g[i][j])Node[i].num ++;
}
Node[i].id = i;
}
sort(Node,Node + n,cmp);
cout<<"Sorted sequence determined after "<<i + 1<<" relations: ";
for(int i = 0;i < n;i ++)cout<<char(Node[i].id + 'A');
cout<<"."<<endl;
res = 1;
break;
}
}
if(res == 0)cout<<"Sorted sequence cannot be determined."<<endl;
}
return 0;
}
上一篇: Java @ 过时注解的作用和可传递性
下一篇: php良好代码风格的阶段性总结
推荐阅读