Problem Author: | Akbar Akbar |
Prepared by: | Hasan Saleh (MathModel) |
Edited by: | Hasan Saleh (MathModel) |
Solution
We need to compute, for each test case, the value
The terms with r=l contribute zero because of the factor (r-l), so we can rewrite the sum over all pairs with a\le l<r\le b. The key step is to remove the XOR using the standard identity
therefore
So the answer becomes
where
To make the notation cleaner, we reindex. Let n = b-a+1 and define x_i = a+i for i=0,\dots,n-1. Any pair (l,r) with a\le l<r\le b corresponds to (x_i,x_j) with 0\le i<j<n, and
Then
For S_1, instead of summing over all pairs, we look at the contribution of each index separately. The element x_k appears in pairs as a right endpoint with i=0,\dots,k-1, and the total distance from those is
It also appears as a left endpoint (k,j) with j=k+1,\dots,n-1, giving
So the total distance weight for index is
and
This is just one loop over , doing everything modulo 10^9+7.
For S_2, we handle bits. We can write
so
where
Fix some bit . Consider only indices where this bit is set. Suppose their indices in increasing order are p_0,p_1,\dots,p_{m-1}. Then
We can compute this in one pass without explicitly storing pairs. When we process p_v, its contribution with all previous indices is
So we maintain for each bit :
\text{cnt}_b = count of indices seen with that bit set (this is ),
\text{sumIdx}_b = sum of those indices,
T_b = accumulated value for this bit.
When we are at index , let x = a + i. For each bit such that the -th bit of is , we update
At the end, T_b is known for each bit, and
with \text{MOD}=10^9+7. The final answer is
Complexity \mathcal{O}(n + n\cdot\log n)
MOD=10**9+7
for _ in range(int(input())):
a,b=map(int, input().split())
n=b-a+1
s1=0
for i in range(n):
l=i*(i+1)//2
r=(n-i-1)*(n-i)//2
w=l+r
s1=(s1+(a+i)%MOD*(w%MOD))%MOD
c=[0]*31
si=[0]*31
t=[0]*31
for i in range(n):
x=a+i
for j in range(31):
if(x>>j&1):
t[j]+=c[j]*i-si[j]
c[j]+=1
si[j]+=i
s2=0
for j in range(31):
s2=(s2+(t[j]%MOD)*((1<<j)%MOD))%MOD
print((s1-s2)%MOD)