【题解】LuoGu6417:mafija

it2025-03-07  31

原题传送门 思路源自luogu初赛模拟卷 贪心从每个入度为0的点开始遍历,删边 整张图就剩下一些环,再处理一下环的情况

Code:

#include <bits/stdc++.h> #define maxn 500010 using namespace std; int n, d[maxn], nxt[maxn], vis[maxn], ans; inline int read(){ int s = 0, w = 1; char c = getchar(); for (; !isdigit(c); c = getchar()) if (c == '-') w = -1; for (; isdigit(c); c = getchar()) s = (s << 1) + (s << 3) + (c ^ 48); return s * w; } void dfs(int u, int sta){ if (vis[u]) return; vis[u] = 1; if (!d[u] && sta) ++ans; --d[nxt[u]]; if (!d[nxt[u]] || sta) dfs(nxt[u], sta ^ 1); } int main(){ freopen("mafija.in", "r", stdin); freopen("mafija.out", "w", stdout); n = read(); for (int i = 1; i <= n; ++i) nxt[i] = read(), ++d[nxt[i]]; for (int i = 1; i <= n; ++i) if (!d[i]) dfs(i, 1); for (int i = 1; i <= n; ++i) if (!vis[i]) dfs(i, 0); printf("%d\n", ans); return 0; }
最新回复(0)