宝塔服务器面板,一键全能部署及管理,送你10850元礼包,点我领取

给定 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 cmpconst node &a,const node &b){ 

return a.num < b.num;
}
int vis[N];
int check){ 

forint i = 0;i < n;i ++)
ifg[i][i] == 1)return -1;//矛盾
forint i = 0;i < n;i ++){ 

forint 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];
whilecin>>n>>m,n || m){ 

int res = 0;
memsetg,0,sizeof g);
forint i = 0;i < m;i ++){ 

cin>>line[i];
}
memsetg,0,sizeof g);
forint i = 0;i < m;i ++){ 

int a = line[i][0] - 'A',b = line[i][2] - 'A';
ifline[i][1] == '<')swapa,b),g[a][b] = 1;
else g[a][b] = 1;
forint i = 0;i < n;i ++)
{ 

ifg[i][a])g[i][b] = 1;
ifg[b][i])g[a][i] = 1;
forint j = 0;j < n;j ++){ 

ifg[i][a] && g[b][j])g[i][j] = 1;
}
}
int flag = check);
ifflag == -1){ 

printf"Inconsistency found after %d relations.\n",i + 1),res = 1;
break;
}
ifflag == 0)continue;
else{ 

forint i = 0;i < n;i ++){ 

Node[i].num = 0;
forint j = 0;j < n;j ++){ 

ifg[i][j])Node[i].num ++;
}
Node[i].id = i;
}
sortNode,Node + n,cmp);
cout<<"Sorted sequence determined after "<<i + 1<<" relations: ";
forint i = 0;i < n;i ++)cout<<charNode[i].id + 'A');
cout<<"."<<endl;
res = 1;
break;
}
}
ifres == 0)cout<<"Sorted sequence cannot be determined."<<endl;
}
return 0;
}