CF755F PolandBall and Gifts
https://www.luogu.com.cn/problem/CF755F
还是有点意思的这题
首先考虑少的,显然每个环先放 c [ i ] / 2 c[i]/2 c[i]/2个
然后再把奇环剩下的散点放了
考虑最小的,如果能找到若干个环大小加起来刚好为 k k k,那么答案就是 n − k n-k n−k, 否则就是 n − k − 1 n-k-1 n−k−1
然后这个用二进制分组优化多重背包即可
可以用bitset优化到 n n l o g n / w n\sqrt{n}logn/w nnlogn/w
#include<bits/stdc++.h>
#define N 1000050
using namespace std;
int n, m, cnt[N], vis[N], a[N], c[N], to[N];
void solve() {
scanf("%d%d", &n, &m);
for(int i = 1; i <= n; i ++) vis[i] = cnt[i] = c[i] = a[i] = 0;
for(int i = 1; i <= n; i ++) scanf("%d", &to[i]);
int gs = 0;
for(int i = 1; i <= n; i ++) if(!vis[i]) {
int x = i;
c[++ gs] = 0;
while(!vis[x]) {
c[gs] ++;
vis[x] = 1;
x = to[x];
}
cnt[c[gs]] ++;
}
int ans = 0;
for(int i = 1; i <= gs; i ++) ans += (c[i] >> 1);
int tot = 0;
for(int i = 1; i <= n; i ++) if(cnt[i]) {
for(int j = 1; cnt[i] >= j; j <<= 1)
a[++ tot] = j * i, cnt[i] -= j;
if(cnt[i]) a[++ tot] = cnt[i] * i;
}
bitset<N> f; f.reset();
f[0] = 1;
for(int i = 1; i <= tot; i ++) {
f |= (f << a[i]);
}
if(f[m]) printf("%d ", m);
else printf("%d ", m + 1);
if(ans >= m) printf("%d", m << 1);
else printf("%d ", (ans << 1) + min(m - ans, n - (ans << 1)));
}
int main() {
solve();
return 0;
}