奇怪了,测试数据都对,但就是通不过。。
#include <iostream>
#include <sstream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <string>
#include <vector>
#include <set>
#include <cctype>
#include <algorithm>
#include <cmath>
#include <deque>
#include <queue>
#include <map>
#include <stack>
#include <list>
#include <iomanip>
using namespace std;
///
///
#define INF 0xffffff7
#define maxn 30
#define max(a,b)(a>b?a:b)
///
int n, m;
vector<int> mapp[maxn];
vector<int> mapp2[maxn];
int cnt;
char sequences[maxn];
int depth;
char relation[5];
int color[maxn];
int quit;
bool flag;
void dfs(int cur)
{
int i, j;
color[cur] = 1;
for (i = 0; i < mapp[cur].size(); i++)
{
int u = mapp[cur][i];
if (color[u] == 1)
{
flag = false;
return;
}
else if (color[u] == 0)
dfs(u);
}
color[cur] = 2;
}
bool dfs2(int cur)
{
int i, j;
color[cur] = 1;
for (i = 0; i < mapp2[cur].size(); i++)
{
int u = mapp2[cur][i];
if (color[u] == 1)
return false;
else if (color[u] == 0 && !dfs2(u))
return false;
}
sequences[depth++] = cur + 'A';
color[cur] = 2;
}
struct path{
int from;
int to;
};
queue<path> qu;
int main()
{
///
int i, j, k;
while (1)
{
scanf("%d %d", &n, &m);
if (n == 0 || m == 0)
break;
for (i = 0; i < maxn; i++)
{
mapp[i].clear();
mapp2[i].clear();
}
while (!qu.empty())
qu.pop();
//m个实例
for (i = 0; i < m; i++)
{
scanf("%s", relation);
int from = relation[0] - 'A';
int to = relation[2] - 'A';
mapp[from].push_back(to);
path temp;
temp.from = from;
temp.to = to;
qu.push(temp);
//进行测试是否有环路
flag = true;
memset(color, 0, sizeof(color));
for (j = 0; j < n; j++)
{
if (color[j] == 0)
dfs(j);
}
if (flag == false)
break;
}
int num = i + 1;
//继续输入
for ( ;i < m - 1; i++)
{
scanf("%s", relation);
int from = relation[0] - 'A';
int to = relation[2] - 'A';
mapp[from].push_back(to);
path temp;
temp.from = from;
temp.to = to;
qu.push(temp);
}
//如果存在环退出
if (flag == false)
{
printf("Inconsistency found after %d relations.\n", num);
continue;
}
//继续寻找路径
for (i = 0; i < m; i++)
{
path tmpPath;
tmpPath = qu.front();
qu.pop();
mapp2[tmpPath.from].push_back(tmpPath.to);
memset(color, 0, sizeof(color));
for (j = 0; j < n; j++)
{
depth = 0;
if (color[j] == 0)
dfs2(j);
if (depth == n)
break;
}
if (depth == n)
break;
}
if (depth < n)
printf("Sorted sequence cannot be determined.\n");
else if (depth == n)
{
printf("Sorted sequence determined after %d relations: ", i + 1);
for (i = depth - 1; i >= 0; i--)
printf("%c", sequences[i]);
printf(".\n");
}
}
///
return 0;
}