【題目描述】
POJ 3370 Halloween treats
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.
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 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.
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 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
Source
Ulm Local 2007
【題目分析】
我們由鴿巢原理的n種玄學推論中的一個:任意m個數中必定存在一個連續的子串和為m的倍數(我也不會證明)可以知道:因為n>=c,所以一定有答案,而且一定存在一個連續的答案,問題現在就是我們如何在很短的時間內找到這個字串。
暴力時間肯定是不允許的,所以我們必須想其他方法。
自己實在想不出來怎么在O(n)O(n)O(n)時間內找到這個串,在一個大佬的博客中見到了一種很巧妙的做法:標記前綴和模c的余數,一旦余數重復出現說明和增加了c的倍數,直接輸出。哇咔咔,這也太強了。ORZ
【AC代碼】
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<iostream>
#include<cmath>
#include<climits>
#include<queue>
#include<vector>
#include<set>
#include<map>
using namespace std;typedef long long ll;
const int MAXN=100005;
int sum,t,c;
int a[MAXN];
int vis[MAXN];
int n;
bool flag;void Print(int l,int r)
{for(int i=l;i<r;i++){printf("%d ",i);}printf("%d\n",r);
}int main()
{while(~scanf("%d%d",&c,&n) && (c || n)){memset(vis,0,sizeof(vis));sum=0;for(int i=1;i<=n;i++){scanf("%d",&a[i]);}for(int i=1;i<=n;i++){sum=(sum+a[i])%c;if(sum%c==0){Print(1,i);break;}else if(vis[sum]){Print(vis[sum]+1,i);break;}vis[sum]=i;}}return 0;
}