Problem Description
抽屉原理,
Every year there is the same problem at Halloween: Each neighbour is only willing to give a certain total number of sweets on that day, no matter how many children call on him, so it may happen that a child will get nothing if it is too late. To avoid conflicts, the children have decided they will put all sweets together and then divide them evenly among themselves. From last year's experience of Halloween they know how many sweets they get from each neighbour. Since they care more about justice than about the number of sweets they get, they want to select a subset of the neighbours to visit, so that in sharing every child receives the same number of sweets. They will not be satisfied if they have any sweets left which cannot be divided.
Your job is to help the children and present a solution.
Your job is to help the children and present a solution.
Input
The input contains several test cases.
The first line of each test case contains two integers c and n (1 ≤ c ≤ n ≤ 100000), the number of children and the number of neighbours, respectively. The next line contains n space separated integers a 1 , ... , a n (1 ≤ a i ≤ 100000 ), where a i represents the number of sweets the children get if they visit neighbour i.
The last test case is followed by two zeros.
The first line of each test case contains two integers c and n (1 ≤ c ≤ n ≤ 100000), the number of children and the number of neighbours, respectively. The next line contains n space separated integers a 1 , ... , a n (1 ≤ a i ≤ 100000 ), where a i represents the number of sweets the children get if they visit neighbour i.
The last test case is followed by two zeros.
Output
For each test case output one line with the indices of the neighbours the children should select (here, index i corresponds to neighbour i who gives a total number of a
i sweets). If there is no solution where each child gets at least one sweet, print "no sweets" instead. Note that if there are several solutions where each child gets at least one sweet, you may print any of them.
分析:
参考《组合数学》鸽巢原理一章中的应用3,我们考虑前k个邻居的糖果总数,那么这样的和一共有n个,a1,a1+a2,...,a1+...+an,如果将他们分别除以孩子的个数c,那么余数只可能在1~c-1之间,换句话说,和有n个,而余数有c-1个,并且从题目中可知c<=n,那么根据抽屉原理可知,必然有两个和的余数是相同的,这也就意味着这两个和中包含的公有项的和能被c整除,即为所求答案,详细推导见书上。
Sample Input
4 5 1 2 3 7 5 3 6 7 11 2 5 13 17 0 0
#include <iostream> #include <cstdio> #include <cstring> #include <cstdlib> #include <algorithm> const int maxx=100010; using namespace std; int c,n; long a[maxx],sum[maxx],flag[maxx]; int main() { int i,t; while(scanf("%d %d",&c,&n)!=EOF){ memset(flag,-1,sizeof(flag));t=0; flag[0]=0;//注意这是一个坑的点,等于0时有点特别 if(c==0&&n==0) break; sum[0]=0; for(i=1;i<=n;i++){ scanf("%ld",&a[i]); sum[i]=(sum[i-1]+a[i])%c; } for(i=1;i<=n;i++){ if(flag[sum[i]]==-1){ flag[sum[i]]=i; } else { long j=flag[sum[i]]+1; for(j=flag[sum[i]]+1;j<=i;j++){ if(j==flag[sum[i]]+1) printf("%ld",j); else printf(" %ld",j); } t=1; break; } } if(t==0) printf("no sweets"); printf("\n"); } return 0; }