[BZOJ 4430] [NWERC 2015] 赌骆驼

[BZOJ 4430] [NWERC 2015] 赌骆驼_第1张图片

Solution:
考虑补集转换:
先令答案为 n * (n - 1), 然后3个序列两两求一次不符合条件的数字对,从ans里除去后就是答案的两倍;
为什么:我们初始时的ans 相当于把 每个数字对 计入两次, 考虑有数字对 i, j 不满足要求的话,它一定会被减去两次,于是得到的ans就是答案的二倍了;
不满足要求的数字对用树状数组统计,很方便的。

Code :

#include <algorithm>
#include <cstring>
#include <cstdlib>
#include <cstdio>

using namespace std;
typedef long long LL;
inline void read(int &x){x=0;char c;while((c=getchar())<'0'||c>'9');for(x=c-'0';(c=getchar())>='0'&&c<='9';x=(x<<1)+(x<<3)+c-'0');}

const int inf = 0x3f3f3f3f ;
const int N = 2e5 + 10 ;

int a[N], b[N], c[N], pos[N], n;

namespace BIT
{
    int c[N];

    void add(int x, int v)
    {
        while (x <= n) c[x] += v, x += x & -x;
    }
    int ask(int x)
    {
        int ret = 0;
        while (x) ret += c[x], x -= x & -x;
        return ret;
    }
}

int main()
{
    #ifdef LX_JUDGE
    freopen("in.txt", "r", stdin);
    #endif
    using BIT::add;
    using BIT::ask;

    read(n);
    LL ret = (LL) n * (n - 1);

    for (int i = 1; i <= n; ++i) read(a[i]);
    for (int i = 1; i <= n; ++i) read(b[i]);
    for (int i = 1; i <= n; ++i) read(c[i]);

    for (int i = 1; i <= n; ++i)
        pos[a[i]] = i;
    for (int i = n, x; i; --i)
    {
        ret -= ask(x = pos[b[i]]), add(x, 1);
    }

    memset(BIT::c, 0, sizeof(BIT::c));

    for (int i = 1; i <= n; ++i)
        pos[b[i]] = i;
    for (int i = n, x; i; --i)
    {
        ret -= ask(x = pos[c[i]]), add(x, 1);
    }

    memset(BIT::c, 0, sizeof(BIT::c));

    for (int i = 1; i <= n; ++i)
        pos[c[i]] = i;
    for (int i = n, x; i; --i)
    {
        ret -= ask(x = pos[a[i]]), add(x, 1);
    }

    printf("%lld\n", ret >> 1);

    return 0;
}

你可能感兴趣的:(想法,bzoj)