Training 8 - D题

Output

#pragma warning (disable:4996)
#include <iostream>
#include <algorithm>
#include <iomanip>
#include <cstring>
#include <string>
#include <cstdio>
#include <cmath>
#include <vector>
#include <queue>
#include <set>
#define inf 0X3f3f3f3f
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int N = 1e4 + 200;
const int M = 2e4 + 200;

vector<int> graph[N];
int deg[N];//入度
int tot, cnt;

int fa[N];
int n, m;
int sum;

vector<pair<int, int>> vec;

int get(int x)
{
if (x == fa[x])
return x;
return fa[x] = get(fa[x]);
}

void merge(int x, int y)
{
fa[get(x)] = get(y);
}

int topsort()
{
int flag = -1;
queue<int> q;
for (int i = 1; i <= n; i++)
if (i == get(i))
{
sum++;
if (deg[i] == 0)
q.push(i);
}
while (q.size())
{
if (q.size() > 1)
flag = 0;//UNCERTAIN
int x = q.front();
q.pop();
++cnt;
for (int i = 0; i < graph[x].size(); i++)
{
int y = graph[x][i];
if (--deg[y] == 0)
q.push(y);
}
}
if (cnt < sum)
flag = 1;//CONFLICT
if (flag != -1)
return flag;
return 2;//OK
}

int main()
{
while (scanf("%d%d", &n, &m) != EOF)
{
for (int i = 1; i <= n; i++)
{
graph[i].clear();
fa[i] = i;
deg[i] = 0;
}
tot = cnt = sum = 0;
for (int i = 1; i <= m; i++)
{
int a, b;
char oper;
scanf("%d %c %d", &a, &oper, &b);
a++, b++;
if (oper == '=')
{
merge(a, b);
continue;
}
if (oper == '<')
swap(a, b);
vec.push_back(make_pair(a, b));
}
while (vec.size())
{
int a = get(vec.back().first);
int b = get(vec.back().second);
graph[a].push_back(b);
deg[b]++;
vec.pop_back();
}
int res = topsort();
if (res == 2)
printf("OK\n");
if (res == 1)
printf("CONFLICT\n");
if (res == 0)
printf("UNCERTAIN\n");
}
return 0;
}

©️2019 CSDN 皮肤主题: 数字20 设计师: CSDN官方博客