ural 1032 鸽巢原理

1032. Find a multiple
Time Limit: 1.0 second
Memory Limit: 16 MB

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
output
5
            1
            2
            3
            4
            1
            
2
            2
            3
            



可以证明一定存在1<=i<j<=n:
(a[i]+a[i+1]+a[i+2]+...+a[j-1]+a[j]) mod n=0
证明:
设b[i]=a[i] mod n,b[0]=0
那么b[x]的范围在[0..n-1]内,但是b有n+1个值(b[0] to b[n])
有鸽巢原理可知一定存在(b[i],b[j])(i!=j),使得b[i]=b[j]
那么
P1=a[1]+a[2]+a[3]+...+a[j]=l*n+b[j]
P2=a[1]+a[2]+a[3]+...+a[i]=k*n+b[i]
那么
P3=P1-P2=a[j]+a[j-1]+a[j-2]+..+a[i+2]+a[i+1]=(l-k)*n+b[j]-b[i]
由于b[j]=b[i]
那么P3=(l-k)*n-------------> P3 mod n=0 !!!
所以算法是计算所有的b(s),并找出对应的i和j
#include <cstdio>
#include 
<cstring>

int a[10001],m[10000];
int n,i,k;

int main() {
    scanf(
"%d",&n);
    memset(m,
-1,sizeof m);
    m[
0]=0;k=0;
    
do{
        a[
0]++;
        scanf(
"%d",&a[a[0]]);
        k
=(k+a[a[0]])%n;
        
if(m[k]==-1) {
            m[k]
=a[0];
        }
else {
            printf(
"%d\n",a[0]-m[k]);
            
for(i=m[k]+1;i<=a[0];i++)
                printf(
"%d\n",a[i]);
            
return 0;
        }
    }
while(true);
    
return 0;
}

posted on 2007-09-25 19:46  woodfish  阅读(766)  评论(1编辑  收藏  举报

导航