POJ 3370. Halloween treats 抽屉原理 / 鸽巢原理

Halloween treats
Time Limit: 2000MS   Memory Limit: 65536K
Total Submissions: 7644   Accepted: 2798   Special Judge


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.


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 a1 , ... , an (1 ≤ ai ≤ 100000 ), where ai represents the number of sweets the children get if they visit neighbour i.

The last test case is followed by two zeros.


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 ai 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.

Sample Input

4 5
1 2 3 7 5
3 6
7 11 2 5 13 17
0 0

Sample Output

3 5
2 3 4







  2、此题数据保证$c\leqslant n$,因此由鸽巢原理,在$mod\ n$环下,令$S(n)=a_1+a_2+\cdots+a_n$,有$S(n_1)=S(n_2)$,即$[S(n_2)-S(n_1)]\%n=a_{n_1+1}+a_{n_1+2}+\cdots+a_{n_2}=0$,所以一定有解。

  3、若此题不保证$c\leqslant n$的约束,则可以出现无解的情况,比如有$5$个孩纸,但只有$1$个邻居$1$颗糖。

  4、若此题不保证$a_i\geqslant 1$的约束,则可以出现某个邻居不给糖的情况($a_i=0$,给$0$颗糖),这样对结果不影响,但输出时可以忽略掉$0$的项。




 1 #include <stdio.h>
 2 #include <string.h>
 4 const int maxn=100100;
 5 int c, n;
 6 int sw[maxn], sum[maxn], sgn[maxn];
 8 int main() {
 9     while(~scanf("%d%d",&c,&n)&&c) {
10         int l=0, r=maxn;
11         memset(sgn, 0xff, sizeof(sgn)); sgn[0]=0;
12         for(int i=1; i<=n; i++) {
13             scanf("%d", sw+i);
14             sum[i]=(sum[i-1]+sw[i])%c;
15             if(!~sgn[sum[i]]) {
16                 sgn[sum[i]]=i;
17             }else if(i-sgn[sum[i]]<r-l) {
18                 l=sgn[sum[i]];
19                 r=i;
20             }
21         }
22         for(int i=l+1; i<r; i++)
23             printf("%d ", i);
24         printf("%d\n", r);
25     }
26     return 0;
27 }
POJ 3370


——本文原创by BlackStorm,转载请注明出处。


posted @ 2016-03-06 11:18  BlackStorm  阅读(...)  评论(...编辑  收藏