Find a multiple
Time Limit: 1000MS | Memory Limit: 65536K | |||
Total Submissions: 5394 | Accepted: 2339 | Special Judge |
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.
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.
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
Source
给你n个数,让你从这些数中找出一些数使他们的和是n的倍数。
令 s1=a1 s2=a1+a2....sn=a1+a2+...+an,这样一共有n个数,考虑他们除以n的余数,余数至多为 0,...c-1 至多有c种,这就是说必然有si sj (i<j) 它们除c的余数是相同的,所以 sj-si能被c整除,sj-si= ai+1 + ai+2...+aj,所以这些数的和是c的倍数。
//504K 79MS
#include<stdio.h>
#include<algorithm>
#define M 10007
using namespace std;
int p[M];
struct sa
{
int mod,num;
}s[M];
int cmp(sa a,sa b)
{
if(a.mod==b.mod)return a.num<b.num;
return a.mod<b.mod;
}
int main()
{
int n,sum;
while(scanf("%d",&n)!=EOF)
{
int k=-1,h;
sum=0;
for(int i=0; i<n; i++)
{
scanf("%d",&p[i]);
sum+=p[i];//对前i个数累加
s[i].mod=sum%n;
s[i].num=i;
if(k==-1&&s[i].mod==0)k=i;//前i个数的和是c的倍数
}
if(k==-1)//没有找到这样的数列
{
sort(s,s+n,cmp);//所有和的余数从小到大排列
for(int i=0; i<n-1; i++)
if(k==-1&&s[i].mod==s[i+1].mod)//如果两个余数相等,则说明他们原来的和是c的倍数
{
k=s[i].num;
h=s[i+1].num;
}
if(k==-1)printf("0\n");
else
{
printf("%d\n",h-k);
for(int i=k+1; i<=h; i++)
printf("%d\n",p[i]);
}
}
else
{
printf("%d\n",++k);
for(int i=0; i<k; i++)
printf("%d\n",p[i]);
}
}
return 0;
}