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. Sample Input 5 1 2 3 4 1 Sample Output 2 2 3 Source 题目大意就是先给出一个数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[2],......,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的值就是答案 然后就利用这个思路就可以直接的解出该题的答案 |
代码:2种情况,满足一种即可
1 #include<cstdio> 2 #include<cstdlib> //没有这个用c写怎么是Compile Error? 3 int num[10000+10]; 4 int sum[10000+10]; 5 int main() 6 { 7 int i,j,k,n; 8 while(scanf("%d",&n)!=EOF){ 9 sum[0]=0;int pos=0; 10 for(i=1;i<=n;++i){ 11 scanf("%d",&num[i]); 12 sum[i]=(sum[i-1]+num[i])%n; 13 if(sum[i]==0)pos=i; 14 } 15 if(pos){ 16 printf("%d ",pos); 17 for(i=1;i<=pos;++i){ 18 printf("%d ",num[i]); 19 } 20 } 21 else { 22 for(i=1;i<=n;++i){ 23 for(j=1;j<i;++j){ 24 if(sum[i]-sum[j]==0)break; 25 } 26 if(j<i)break; 27 } 28 printf("%d ",i-j); 29 for(int k=j+1;k<=i;++k){ 30 printf("%d ",num[k]); 31 } 32 } 33 } 34 return 0; 35 }