Olympiad in Informatics

CH3801: Rainbow's Signal — Solution

Main Idea

This problem is pretty interesting; at the end of the day it all comes down to bitwise operations. First, a sufficient conclusion is that the probability of picking an interval of length \(1\) is \(\frac{1}{N^2}\), while for length greater than 1 it is \(\frac{2}{N^2}\). Then, enumerate over the length of an \(int\), \(i \in [0,30]\), put the \(i\)-th bit of every number into a sequence and scan it, and when the scan reaches the \(j\)-th number, do case analysis.

  • If the operator is \(and\), we let \(last[0]\) be the position of the last \(0\); in between there are \(k-last[0]+1\) numbers in total that give 1 when combined with it. Multiply by the probability and update the answer.
  • If the operator is \(or\), just multiply the interval probability directly by \(i-1\).
  • If the operator is \(xor\), we need to split the preceding \(0,1\) into blocks. Let \(c_1,c_2\) be the sums of the preceding interval lengths, where the intervals of \(c_1\) and \(c_2\) do not overlap and alternate. Each time, just multiply by the corresponding block length; for a \(1\), swap the blocks, and for a \(0\), leave them as they are.

Code

// CH3801.cpp
#include <bits/stdc++.h>
using namespace std;
const int MAX_N = 1e5 + 200;
int n, arr[MAX_N];
double ans1, ans2, ans3;
int main()
{
    scanf("%d", &n);
    for (int i = 1; i <= n; i++)
        scanf("%d", &arr[i]);
    for (int k = 0; k < 30; k++)
    {
        int last[2], c1 = 0, c2 = 0;
        last[0] = last[1] = 0;
        for (int i = 1; i <= n; i++)
            if ((arr[i] >> k) & 1)
            {
                ans1 += (1 << k) * 1.0 / n / n;
                ans2 += (1 << k) * 1.0 / n / n;
                ans3 += (1 << k) * 1.0 / n / n;
                ans1 += (1 << k) * 2.0 / n / n * c1;
                ans2 += (1 << k) * 2.0 / n / n * (i - 1);
                ans3 += (1 << k) * 2.0 / n / n * (i - 1 - last[0]);
                last[1] = i;
                c1++, swap(c1, c2);
            }
            else
            {
                ans1 += (1 << k) * 2.0 / n / n * c2;
                ans2 += (1 << k) * 2.0 / n / n * (last[1]);
                last[0] = i, c1++;
            }
    }
    printf("%.3lf %.3lf %.3lf", ans1, ans3, ans2);
    return 0;
}