冯兴楠 • 1年前
using namespace std; const int MAXN = 30, MAXM = 610; int ind[MAXN], h[MAXN], ans[MAXN], n, m, idx; bool st[30][30];
struct CharRec { //存储读入的限制条件中的对应的顶点编号
int u, v;
} e[MAXN];
struct rec {
int to, nxt;
} edge[MAXM];
queueq;
void add(int x, int y) {
edge[idx].to = y;
edge[idx].nxt = h[x];
h[x] = idx++;
}
void init() {
char x, y, z;
cin >> n >> m;
for (int i = 1; i <= m; i++) {
cin >> x >> y >> z;
if (st[x - 'A' + 1][z - 'A' + 1])
continue;
st[x - 'A' + 1][z - 'A' + 1] = 1;
e[i].u = x - 'A' + 1;
e[i].v = z - 'A' + 1;
add(e[i].u, e[i].v);
}
}
int topsort() {
int num = 0, flag = 0, temp = 0; //num记数,flag讨论三种情况,temp临时
for (int i = 1; i <= n; i++) {
if (ind[i] == 0) {
q.push(i);
num++;
}
}
if (num > 1)
flag = 1; //用1来表示入度为0的点不止一个。
while (!q.empty()) {
num = 0;
for (int i = h[q.front()]; i != -1; i = edge[i].nxt) {
int v = edge[i].to;
ind[v]--;
if (ind[v] == 0) {
q.push(v);
num++;
}
}
if (num > 1)
flag = 1; //同时产生的入度为0顶点不止一个。
ans[++temp] = q.front();
q.pop();
}
if (temp < n)
return -1;//存在环 返回-1
else if (flag == 1)
return 0;
else
return 1;
}
void work() {
memset(h, -1, sizeof h);
for (int i = 1; i <= m; i++) {
memset(ind, 0, sizeof ind);
memset(ans, 0, sizeof ans);
add(e[i].u, e[i].v);
for (int j = 1; j <= i; j++)
ind[e[j].v]++;
int f = topsort();
if (f == -1) { //存在环
cout << "Inconsistency found after " << i << " relations." << endl;
return;
} else if (f == 1) { //确定了拓扑排序,输出
cout << "Sorted sequence determined after " << i << " relations: ";
for (int j = 1; j <= n; j++)
cout << char(ans[j] + 'A' - 1);
cout << "." << endl;
return;
} else
continue; //继续增加一条边进行判断
}
cout << "Sorted sequence cannot be determined." << endl;
return;
}
int main() {
init();
work();
return 0;
}
评论:
请先登录,才能进行评论