CF1876C Tutorial
SlayedDrawer · · 题解
一道可能比较套路的题目。
一开始我并没有往图的方向想。但是不妨碍得出正解。
由于嵌套下标有点多,故使用
首先我们发现,可能存在这么一些数,使得除了自己之外其他的数都不跟它的下标相等。数学化一点的语言来讲就是对于
显然,这些点是不能被圈起来的,否则肯定会造成无解。
那么这些点如果没有被圈起来,那么根据题意,他们所代表的数
那么由于
这里可能比较绕,但是相信大家应该也能看出来这里与图的联系:如果
此时我们剩下的,如果按照上面的连边方式,很显然就是一个个的环。我们就可以尝试交替处理:如果将
所以总的时间复杂度为
我的写法可能细节比较多,赛时吃了三发罚时,或者叫罚分吧。
#include<bits/stdc++.h>
using namespace std;
const int N = 2e5 + 204;
int n, a[N], cnt[N], q[N << 1], head = 1, tail = 0;
int tag[N];
bool inq[N];
// 0 : undef
// 1 : white node
// 2 : black node
int main() {
scanf("%d", &n);
for(int i = 1; i <= n; i++)
scanf("%d", &a[i]), cnt[a[i]]++;
for(int i = 1; i <= n; i++)
if(!cnt[i] || (cnt[i] == 1 && a[i] == i))
q[++tail] = i, inq[i] = 1;
while(head <= tail) {
int x = q[head++];
tag[x] = 1;
if(a[x] == x) {
printf("-1\n");
return 0;
}
if(tag[a[x]] == 1) {
printf("-1\n");
return 0;
}
if(!tag[a[x]])
tag[a[x]] = 2,
--cnt[a[a[x]]];
if(!inq[a[a[x]]] && tag[a[a[x]]] == 0 && (!cnt[a[a[x]]] || (cnt[a[a[x]]] == 1 && a[a[a[x]]] == a[a[x]])))
q[++tail] = a[a[x]], inq[a[a[x]]] = 1;
}
for(int i = 1; i <= n; i++) {
if(!tag[i]) {
int len = 1;
int pos = i;
while(a[pos] != i)
++len,
pos = a[pos];
if(len % 2) {
printf("-1\n");
return 0;
}
int num = 2; pos = i;
tag[pos] = num;
while(a[pos] != i)
num = 3 - num,
tag[a[pos]] = num,
pos = a[pos];
}
}
int cnt = 0;
for(int i = 1; i <= n; i++)
if(tag[i] == 1)
++cnt;
if(cnt == n)
printf("-1\n");
else {
printf("%d\n", cnt);
for(int i = 1; i <= n; i++)
if(tag[i] == 1)
printf("%d ", a[i]);
}
return 0;
}