Codeforces 755F PolandBall and Gifts bitset + 二进制优化多重背包

PolandBall and Gifts

转换成置换群后, 对于最大值我们很好处理。

对于最小值, 只跟若干个圈能否刚好组能 k 有关。

最直观的想法就是bitset优化背包, 直接搞肯定T掉。

我们能再发掘一些性质, 就是本质不能的圈的大小最多有sqrt(n)个,

因为1 + 2 + 3 ... + n = (n + 1) * n / 2

所以对于每个不同的数二进制优化一下就可以过啦。 

感觉这种题就很有意思。。

#include<bits/stdc++.h>
#define LL long long
#define LD long double
#define ull unsigned long long
#define fi first
#define se second
#define mk make_pair
#define PLL pair<LL, LL>
#define PLI pair<LL, int>
#define PII pair<int, int>
#define SZ(x) ((int)x.size())
#define ALL(x) (x).begin(), (x).end()
#define fio ios::sync_with_stdio(false); cin.tie(0);

using namespace std;

const int N = 1e6 + 7;
const int inf = 0x3f3f3f3f;
const LL INF = 0x3f3f3f3f3f3f3f3f;
const int mod = 1e9 + 7;
const double eps = 1e-8;
const double PI = acos(-1);

template<class T, class S> inline void add(T& a, S b) {a += b; if(a >= mod) a -= mod;}
template<class T, class S> inline void sub(T& a, S b) {a -= b; if(a < 0) a += mod;}
template<class T, class S> inline bool chkmax(T& a, S b) {return a < b ? a = b, true : false;}
template<class T, class S> inline bool chkmin(T& a, S b) {return a > b ? a = b, true : false;}

int n, k, p[N], c[N], num[N], cnt;
bool vis[N];
bitset<1000001> dp;
vector<int> oo;

int main() {
    scanf("%d%d", &n, &k);
    for(int i = 1; i <= n; i++) scanf("%d", &p[i]);
    for(int i = 1; i <= n; i++) {
        if(vis[i]) continue;
        int u = i; cnt++;
        while(!vis[u]) {
            vis[u] = true;
            c[cnt]++;
            u = p[u];
        }
    }
    int one = 0, two = 0;
    for(int i = 1; i <= cnt; i++)
        (c[i] & 1) ? one++, two += c[i] / 2 : two += c[i] / 2;
    int mnans = 0, mxans = 0;
    if(two >= k) mxans = 2 * k;
    else {
        mxans += two * 2 + (k - two);
        chkmin(mxans, n);
    }
    dp[0] = 1;
    for(int i = 1; i <= n; i++) oo.push_back(c[i]);
    sort(ALL(oo)); oo.erase(unique(ALL(oo)), oo.end());
    for(int i = 1; i <= n; i++) num[lower_bound(ALL(oo), c[i]) - oo.begin()]++;
    for(int i = 0; i < SZ(oo); i++) {
        for(int j = 0; (1 << j) <= num[i]; j++) {
            int val = (1 << j) * oo[i];
            num[i] -= 1 << j;
            dp |= dp << val;
        }
        if(num[i]) {
            int val = num[i] * oo[i];
            dp |= dp << val;
        }
    }
    mnans = dp[k] ? k : k + 1;
    printf("%d %d\n", mnans, mxans);
    return 0;
}

/*
*/

猜你喜欢

转载自www.cnblogs.com/CJLHY/p/10749738.html