原题链接:
https://vjudge.net/problem/POJ-2912
AC代码:
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <list>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
const int INF = 0x3fffffff;
typedef long long ll;
typedef unsigned long long ull;
void __init__()
{
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
} //head
const int maxn = 2021;
int f[maxn], a[maxn], b[maxn];
char ch[maxn];
int n, m;
int find(int x)
{
return f[x] == x ? x : f[x] = find(f[x]);
}
void uni(int x, int y)
{
int fx = find(x);
int fy = find(y);
if (fx != fy)
f[fy] = fx;
}
int check(int x)
{
//并查集初始化
for (int i = 0; i < n * 3; i++)
{
f[i] = i;
}
//对于每轮次,判断若x为judge时,是否满足条件(不冲突)
for (int i = 1; i <= m; i++)
{
if (a[i] == x || b[i] == x)
continue;
if (ch[i] == '>')
{
//不冲突
if (find(a[i]) == find(b[i] + n))
continue;
//在第i轮次被发现有矛盾
else if (find(a[i]) == find(b[i] + 2 * n) || find(a[i]) == find(b[i]))
{
return i;
}
//同类合并
else
{
uni(a[i], b[i] + n);
uni(a[i] + n, b[i] + 2 * n);
uni(a[i] + 2 * n, b[i]);
}
}
if (ch[i] == '<')
{
//不冲突
if (find(a[i]) == find(b[i] + 2 * n))
continue;
else if (find(a[i]) == find(b[i] + n) || find(a[i]) == find(b[i]))
{
return i;
}
else
{
uni(a[i], b[i] + 2 * n);
uni(a[i] + n, b[i]);
uni(a[i] + 2 * n, b[i] + n);
}
}
if (ch[i] == '=')
{
//不冲突
if (find(a[i]) == find(b[i]))
continue;
else if (find(a[i]) == find(b[i] + n) || find(a[i]) == find(b[i] + 2 * n))
{
return i;
}
else
{
uni(a[i], b[i]);
uni(a[i] + n, b[i] + n);
uni(a[i] + 2 * n, b[i] + 2 * n);
}
}
}
return 0;
}
int main()
{
// __init__();
while (scanf("%d%d", &n, &m) != EOF)
{
for (int i = 1; i <= m; i++)
{
scanf("%d%c%d", &a[i], &ch[i], &b[i]);
}
vector<int> ans;
int rnd = 0;
for (int i = 0; i < n; i++)
{
int rsl = check(i);
if (rsl == 0)
{
ans.push_back(i);
}
//max表示最坏情况
else
{
rnd = max(rnd, rsl);
}
}
if (ans.empty())
{
printf("Impossible\n");
}
else if (ans.size() > 1)
{
printf("Can not determine\n");
}
else
{
printf("Player %d can be determined to be the judge after %d lines\n", ans[0], rnd);
}
}
return 0;
}
日常补题
本题考察并查集的应用,跟之前做过的一道叫 食物链的题很像POJ-1182 食物链
虽然以前做过类似的,但这题训练的时候也没做出来 难受orz 这个代码是参考的马队的代码,大体思路就是遍历每一个人,并假设他是judge,判断一下在他是裁判的情况下,是否会产生冲突(产生冲突说明不满足条件),同时记录矛盾发生的轮次,若没有产生冲突,说明当前编号的人可以当裁判,在所有产生冲突的轮次中,最大值为发现该裁判的必要轮次(最坏情况),最后判断ans,若为空说明impossible 若答案大于一个(只能有一个裁判),则无法判断。