CDOJ 1041 Hug the princess 【思维】

题目链接:CDOJ 1041 Hug the princess

题意:求解 ni=1 a[i] ^ a[j] + a[i] | a[j] + a[i] & a[j]。

思路:a ^ b + a | b + a & b = a + b + a | b - a & b。先统计a + b的贡献,而a | b + a & b的贡献则是每个二进制位上1的个数,最后累加一下就好了。

AC代码:

#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <queue>
#include <set>
#define CLR(a, b) memset(a, (b), sizeof(a))
#define fi first
#define se second
using namespace std;
typedef long long LL;
typedef pair<int, int> pii;
const int MAXN = 1e5 +10;
const int INF = 0x3f3f3f3f;
const int MOD = 1e9 + 7;
void add(LL &x, LL y) { x += y; x %= MOD; }
LL a[MAXN], sum[MAXN], bit[MAXN][41], sbit[41];
int main()
{
    int n;
    while(scanf("%d", &n) != EOF) {
        sum[0] = 0;
        for(int j = 0; j <= 40; j++) {
            bit[0][j] = 0; sbit[j] = 0;
        }
        for(int i = 1; i <= n; i++) {
            scanf("%lld", &a[i]);
            sum[i] = sum[i-1] + a[i];
            for(int j = 0; j <= 40; j++) {
                bit[i][j] = 0;
                if(a[i] & (1LL << j)) {
                    bit[i][j] = 1;
                }
                bit[i][j] += bit[i-1][j];
            }
        }
        LL ans = 0;
        for(int i = 1; i < n; i++) {
            ans += (n - i) * a[i] + sum[n] - sum[i];
            for(int j = 0; j <= 40; j++) {
                int num = bit[n][j] - bit[i][j];
                if(a[i] & (1LL << j)) {
                    sbit[j] += n - num - i;
                }
                else {
                    sbit[j] += num;
                }
            }
        }
        LL res = 0;
        for(int i = 0; i <= 40; i++) {
            res += sbit[i] * (1LL << i);
        }
        printf("%lld\n", ans + res);
    }
    return 0;
}

你可能感兴趣的:(CDOJ 1041 Hug the princess 【思维】)