LosingGame's blog

By LosingGame, history, 5 years ago, In English

Hi,
How to solve Quadruple Counting . I read the editorial but couldn't understand . Any help will be appreciated. Thanks

Tags #dp
  • Vote: I like it
  • 0
  • Vote: I do not like it

»
5 years ago, # |
Rev. 2   Vote: I like it 0 Vote: I do not like it

Its really interesting problem. And interesting solution. It's pretty easy to come with O(n^2) solution, but time limits are really strict, so it won't fit. You need something like O(n*sqrt(max(Ai)) suggested by Editorial to fit (actually it's more like O(n*sqrt(max(Ai))*log(max(Ai))) since we have dp[n][maxA][log(maxA)]). Editorial suggests some mix of divide&conquer (that looks like the one used in simple problem of finding pairs in array that sum up to a given target-value) and DP. Let's look at this function:

void calcAnd() {
    memset(dp, 0, sizeof dp);
    ll nwVal = 0;

// MAIN LOOP
    for (int i = 1, f, s; i <= n; i++) {
        f = (a[i] & ((1 << 8) - 1));
        s = (a[i] >> 8);
        nwVal = 0;
// FIRST LOOP
        for (int prevF = 0; prevF < (1 << 8); prevF++) {
            if (cnt[prevF & f] > b[i] || b[i] - cnt[prevF & f] > 8)
                continue;
            nwVal += dp[prevF][s][b[i] - cnt[prevF & f]];
        }
// SECOND LOOP
        for (int nextS = 0; nextS < (1 << 8); nextS++) {
            dp[f][nextS][cnt[nextS & s]] += val[i];
        }
        val[i] = nwVal;
    }
}

From start val[i] initialized with 1s, dp with 0s, and cnt[i] is array with values equal to number of 1s in binary representation of integer "i". "Main loop" goes over every element of array a[] and first divides a[i]<2^16 bitwise into two parts f-first 8 bits of a[i] and s-second 8 bits of a[i]. Than algorithm goes through two loops: "first loop" is taking values from DP and adds them to get result in val[i]; "second loop" puts values into DP.

Now what are those values? For each f (first part of a[i]) and every possible 8bit number (_nextS_ from 0 to 2^8) we put val[i]=1 in dp[][][cnt] corresponding to number of ones in F(f,nextS). And we overwrite val[i] with nwVal, which is either zero or number of variations for i-th element. And in first loop for every possible 8bit number prevF we compute (b[i] — cnt[prevF & f]) — number of ones we need to add up to b[i]. If prevF really was some f(a[j]) (where j<i) then there is some number in DP[prevF][s][] — number of variants for i-th element that satisfy previous steps. And we add all of that numbers and put it back in v[i]. In this way we get number of all i-s for every j in array val[].

Then we run similar function calcOr() and find number of all (i,j) pairs for every k in the same array val[]. And running calcAnd() we get numbers for every l and we add up all those values in final val[] to get final result.