简单定义: “如果有五个鸽子笼,养鸽人养了6只鸽子,那么当鸽子飞回笼中后,至少有一个笼子中装有2只鸽子。”这个简单的事实就是著名的鸽笼原理,在我们国家更多地称为抽屉原理。
对于这道题,我们先设sum[1]=a[1],sum[2]=a[1]+a[2],sum[3]=a[1]+a[2]+a[3],sum[n]=a[1]+a[2]+…a[n];
如果存在sum[i]正好是n的倍数,直接输出就是,但若没有存在,则sum[i]%n必定属于[1,n-1],因为sum[i]有n项,那么鸽笼原理来了,由鸽笼原理知必定有一对sum[i]==sum[j]&&i!=j,而这两个sum的差也就是n的倍数;所以只需要输出i+1到j的值即可,也解释了为啥没有不可能的情况。
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
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn=1e4+5;
int main()
{
int n;
scanf("%d",&n);
int sum[maxn],a[maxn];
bool flag=false;
int solve;
for(int i=0;i<n;i++)
{
scanf("%d",&a[i]);
if(a[i]%n==0) { //单个值成立
flag=true;
solve=a[i];
}
if(i==0) sum[i]=a[i]%n;
else sum[i]=(sum[i-1]+a[i]%n)%n;
}
if(flag) {
printf("1\n%d\n",solve);
return 0;
}
int done[maxn];
memset(done,-1,sizeof(done));
int l,r;
for(int i=0;i<n;i++)
{
if(sum[i]==0) { //前缀和的余成立
flag=true;
l=0,r=i;
break;
}
}
if(flag) {
printf("%d\n",r-l+1);
for(int i=0;i<=r;i++)
{
printf("%d\n",a[i]);
}
return 0;
}
for(int i=0;i<n;i++)
{
if(done[sum[i]]==-1) { //鸽笼定理,计算余数相等的区间操作,使用done数组标记出现过的余数,
done[sum[i]]=i;
}
else {
l=done[sum[i]]+1;
r=i;
flag=true;
break;
}
}
printf("%d\n",r-l+1);
for(int i=l;i<=r;i++)
{
printf("%d\n",a[i]);
}
return 0;
}