Find a multiple
Description 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. Sample Input Sample Output Source |
[Submit] [Go Back] [Status] [Discuss]
All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator
题意:给出n个数,任选几个数,使其和为n的倍数。
解析:鸽巢原理的简单应用。
总共有N个数。
输入的数据存为 a[1] a[2] .........a[N]
令 sum[n]=(a[1]+a[2]+a[3]+...+a[n])%N (n=1,2,3,...,N)
首先,sum[n]都是N的余数。
总共有N个取值(0,1,2,...,N-1)。
而 sum[1],sum[2],...,sum[N]共有N个数。(这里就是抽屉原理的应用,可将n-1个余数看成n个抽屉,将n(也即是sum[i])个数看成苹果,那么肯定存在某个抽屉里有至少2个苹果)。
根据鸽笼原理,必存在 i < j 使得 sum[ i ]=sum[ j ] (sum[i]%n)=(sum[j]%n),即(sum[i]-sum[j])%n=0,即前 i 个数的和的余数等于前 j 个数的和的余数,则从 第 i+1个数到第 j 个数的和的余数=0;
则 a[ i+1],a[ i+2],...,a[ j ] 即为所求。
#include<bits/stdc++.h>
using namespace std;
#define e exp(1)
#define pi acos(-1)
#define mod 1000000007
#define inf 0x3f3f3f3f
#define ull unsigned long long
#define ll long long
int a[10000+10];
int sum[10000+10];
int main()
{
int n;
while(scanf("%d",&n)==1)
{
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
memset(sum,0,sizeof(sum));
if(n==1&&a[1]==0)
{
printf("0\n");
continue;
}
for(int i=1;i<=n;i++)
{
sum[i]=sum[i-1]+a[i];
sum[i]=sum[i]%n;
}
int flag=0;
for(int i=1;i<=n;i++)
{
if(sum[i]==0)
{
printf("%d\n",i);
for(int j=1;j<=i;j++)
{
printf("%d\n",a[j]);
}
printf("\n");
flag=1;
break;
}
}
if(!flag)
{
for(int i=1;i<=n;i++)
{
for(int j=i+1;j<=n;j++)
{
if(sum[i]-sum[j]==0)
{
flag=1;
printf("%d\n",j-i);
for(int k=i+1;k<=j;k++)
{
printf("%d\n",a[k]);
}
break;
}
}
if(flag)
break;
}
}
if(flag==0)
printf("0\n");
}
return 0;
}