首页 > 技术文章 > hdu6059[字典树+思维] 2017多校3

UnderSilenceee 2017-08-02 16:36 原文

#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
int trie[31 * 500005][2];
int no[31 * 500005];
int sz[31 * 500005];
int sum[31][2];
int T, n, temp, tot = 0;
LL ans = 0;
void solve(int x) {
    int now = 0;
    for (int i = 29; ~i; i--) {
        int bit = (x & (1 << i)) ? 1 : 0;
        sum[i][bit]++;
        if (!trie[now][bit]) {
            trie[now][bit] = ++tot;
        }
        if (trie[now][1 ^ bit]) { //存在兄弟节点,即有符合的(Ai,Aj)
            int bro = trie[now][1 ^ bit];
            ans += 1LL * sz[bro] * (sz[bro] - 1) / 2;
            ans += 1LL * (sum[i][1 ^ bit] - sz[bro]) * sz[bro] - no[bro];
        }
        now = trie[now][bit];
        sz[now]++;
        no[now] += sum[i][bit] - sz[now];//除去不符合j>i的(Ai,Aj),要累加
        //cout << now << ' ' << no[now] << endl;
    }
}
void init() {
    memset(trie, 0, sizeof(trie));
    memset(no, 0, sizeof(no));
    memset(sum, 0, sizeof(sum));
    memset(sz, 0, sizeof(sz));
    ans = 0, tot = 0;
}
int main() {
    scanf("%d", &T);
    while (T--) {
        init();
        scanf("%d", &n);
        for (int i = 0; i < n; i++) {
            scanf("%d", &temp);
            solve(temp);
        }
        printf("%lld\n", ans);
    }
}

 

推荐阅读