Ques. Divisible Subset
To find a non-empty subset of the given multiset with the sum of
elements divisible by the size of original multiset.
Hint:
a % N = x
b % N = x
Then, (b-a) % N = (b % N - a % N) = (x - x) = 0
Let’s denote a1 + a2 + … + ak by bk. So, we obtain:
b0 = 0
b1 = a1
b2 = a1 + a2
.
.
.
.
bN = a1 + a2 + a3 + a4 +…+ aN
so, aL + aL+1 + … + aR = bR - bL-1
Therefore, if there are two values with equal residues modulo N among
b0, b1, …, bN then we take the first one for L-1 and the second one for
R and the required subsegment is found.
There are N+1 values of bi and N possible residues for N. So,
according to the pigeonhole principle the required subsegment will
always exist.
Code
#include<bits/stdc++.h>
using namespace std;
#define N (1e6+10)
vector pos(N, -1);
vector v;
vector pre;
int main(){
int t,n,x,l = 0,r = 0;
scanf("%d",&t);
while(t–){
scanf("%d",&n);
for(int i = 0;i<n;i++){
scanf("%d",&x);
v.push_back(x % n);
}
//Pre vector denotes the prefix sum bi
pre.push_back(0);
for(int i = 0;i<n;i++)
pre.push_back((pre[i] + v[i]) % n);
//Position vector denotes the index of
//each segment sum
for(int i = 0;i<n+1;i++){
//If this segement sum is encountered first t
ime
if(pos[pre[i]] == -1){
pos[pre[i]] = i;
}
//If this segment sum has already been encoun
tered
//we have our answer.
//L will be its previous index and R current
index
else{
//pos[pre[i]] will give L-1
l = pos[pre[i]] + 1;
r = i;
break;
}
}
//Number of elements in the segment
//is (R-L+1)
printf("%d\n",r - l + 1);
//Print the index between l and r
for(int i = l;i<=r;i++)
printf("%d “,i);printf(”\n");
v.clear();
pre.clear();
for(int i = 0;i<=n;i++)pos[i] = -1;
}
return 0;
}
In this question pos vector is initially given value -1; the how can we change value later,also tell what exactly what method are we using in this question
@goyal431 vectors work just like arrays. If you want to rewrite any value later you can simply do it like pos[i] = 6;
We are using the pigeonhole principle in this question, you can watch this https://www.youtube.com/watch?v=p5Cm_r4T1Rw&t=625s video for better understanding of this algorithm.
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.