Find a multiple (鸽巢原理)

鸽巢原理:
基本描述

桌子上有十个苹果,把这十个苹果放到九个抽屉里,无论怎么放,我们会发现至少会有一个抽屉里面至少放两个苹果。这一现象就是所说的“抽屉原理”。

更一般的表述:如果每一个抽屉代表一个集合,每一苹果就可以代表一个元素。加入有n+1个元素放到n个集合中去,其中必定有一个集合里至少有两个元素。

第一抽屉原理

原理1

把多余n+1个物体放到n个抽屉里,则至少有一个抽屉里的东西不少于两件。

原理2

把多余m*n+1(n不为0)个物体放到n个抽屉里面,则至少有一个抽屉里面不少于(m+1)个物体

第二抽屉原理

把(m*n-1)个物体放入n个抽屉中,其中必须有一个抽屉不多于(m-1)个物体。

如将3*5-1=14个物体放入5个抽屉中,则必定有一个抽屉中的物体数目少于3-1=2.

例题Find a multiple 

The input contains N natural (i.e. positive integer) numbers ( N <= 10000 ). Each of that numbers is not greater than 15000. This numbers are not necessarily different (so it may happen that two or more of them will be equal). Your task is to choose a few of given numbers ( 1 <= few <= N ) so that the sum of chosen numbers is multiple for N (i.e. N * k = (sum of chosen numbers) for some natural number k).

Input

The first line of the input contains the single number N. Each of next N lines contains one number from the given set.

Output

In case your program decides that the target set of numbers can not be found it should print to the output the single number 0. Otherwise it should print the number of the chosen numbers in the first line followed by the chosen numbers themselves (on a separate line each) in arbitrary order. 

If there are more than one set of numbers with required properties you should print to the output only one (preferably your favorite) of them.

Sample Input

5
1
2
3
4
1

Sample Output

2
2
3

题目大意就是先给出一个数N,接着再给出N个数,要你从这N个数中任意选择1个或者多个数,使得其和是N的倍数

如果找不到这样的答案则输出0

答案可能有多个,但任意输出一个解就行。

输出的第一行是选择元素的个数M,接着M行分别是选择的元素的值

此题是不存在输出0的结果

证明如下

我们可以依次求出a【0】,a【0】+a【1】,a【0】+a【1】+a【2】.............a【0】+a【1】+a【2】...+a【n】;

假设分别是sum【0】,sum【1】,.........sum【n】

如果在某一项存在的是N的倍数,则很好解,即可直接从第一项开始直接输出答案

但如果不存在,则sum【i】%N的值必定在【1,N-1】之间,又由于n项sum,有抽屉原理:

把多于n个的物体放到n个抽屉里,则至少有一个抽屉里有2个或2个以上的物体。

则必定有一对i,j,使得sum【i】=sum【j】,其中i!=j,不妨设j>i

则(sum【j】-sum【i】)%N=0,故sum【j】-sum【i】是N的倍数

则只要输出i+1~j的所有的a的值就是答案

代码:

#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
	int N,a[100000],sum[100000],b[100000];//b数组是进行标记 sum数组是取膜后的前缀和 
	cin>>N;
	memset(a,0,sizeof(a));//对数组进行初始化 
	memset(sum,0,sizeof(sum));
	memset(b,0,sizeof(b));
	for(int i=1;i<=N;i++)
	{
		cin>>a[i];
		sum[i]=(sum[i-1]+a[i])%N;//类似动态dp 相加取余数 如果sum中出现有俩值相等就是表明已经进行了一个循环 
	}
	for(int i=1;i<=N;i++)
	{
		if(sum[i]==0)
		{
			cout<<i<<endl;
			for(int j=1;j<=i;j++)
			{
				if(j!=1)  printf("%d\n",a[j]);
				else printf("%d\n",a[j]);
			}
			break;
		}
		if(b[sum[i]]==0)
		{
			b[sum[i]]=i;
		}
		else
		{
			cout<<i-b[sum[i]]<<endl;
			for(int j=b[sum[i]]+1;j<=i;j++)
			{
				if(j!=b[sum[i]]+1) printf("%d\n",a[j]);
				else printf("%d\n",a[j]);
			}
			break;
		}
	}
	return 0;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值