鸽巢原理应用-分糖果 POJ 3370 Halloween treats


基本原理:n+1只鸽子飞回n个鸽笼至少有一个鸽笼含有不少于2只的鸽子。

很简单,应用却也很多,很巧妙,看例题:

 

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 containsn 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 aisweets). 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

 

题目大意:糖果平分问题。有c个小孩,n个提供糖果的邻居,你可以选择要或不要。现在你只考虑得到的全部糖果能否平分,可能有多种方案,输出一种即可。


上面的case 1: 结果 2 3 4 也行,总和为12. 输出一种即可



 

#include <stdio.h>

#include <algorithm>

using namespace std;



int c,n,neigb[100001];

int S;

struct Remnant

{

	int h,r; // 下标和余数

}R[100001];



bool cmp(const Remnant &a, const Remnant & b){ //按余数从小到大排序

	if( a.r == b.r)

		return a.h < b.h;

	return a.r < b.r;

}



int main(){

	//freopen("in.txt","r",stdin);

	while(scanf("%d %d", &c, &n) != EOF){

		if(c==0 && n==0) break;

		int k=-1,h;

		S=0;

		for(int i=0; i<n; i++)

		{

			scanf("%d",&neigb[i]);

			S += neigb[i];

			R[i].r = S%c; //存储是前i个和 对c的余数

			R[i].h = i + 1; //h 为下标

			if(k == -1 && R[i].r==0 ) k=i;

		}



		if(k == -1){

			sort(R, R+n, cmp);

			for(int i=0; i<n-1; i++)

			{

				if(k == -1 && R[i].r == R[i+1].r) 

				{

					k = R[i].h;

					h = R[i+1].h;

					break;

				}

			}

			if(k==-1)

				printf("no sweets\n");

			else{

				for(int i=k+1; i<h; i++)

					printf("%d ",i);

				printf("%d\n",h);

			}

		}else{

			for(int i=0; i<k; i++)

				printf("%d ",i+1);

			printf("%d\n",k+1);

		}



		

	}

	return 0;

}


 




 

你可能感兴趣的:(poj)