现在的位置: 首页 > 综合 > 正文

pku 2356 Find a multiple (鸽巢原理)

2014年10月22日 ⁄ 综合 ⁄ 共 1546字 ⁄ 字号 评论关闭
Find a multiple
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 5057   Accepted: 2192   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.

Sample Input

5
1
2
3
4
1

Sample Output

2
2
3

Source

题意:n个数任意取m个数使其是n的倍数
题解:Sk表示a1+a2+……ak,如果Sk是n的倍数,那就直接取Sk了,否则S1-Sn除n的余数分布在1---(n-1)这n-1个数中,
根据鸽巢原理,必然有两个的余数相同,即(Si%n)=(Sj%n),即(Sj-Si)%n=0,证毕。

#include<stdio.h>
#include<string.h>
int n,c[10005],mark[10005];
int main()
{
    int i,j,x,y,flag;

    while(scanf("%d",&n)>0)
    {
        memset(mark,0,sizeof(mark));
        for(flag=c[0]=0,i=1;i<=n;i++)
        {
            scanf("%d",&x);
            if(flag) continue;
            c[i]=c[i-1]+x;
            if(c[i]%n==0)
            {
                printf("%d\n",i);
                for(j=1;j<=i;j++) printf("%d\n",c[j]-c[j-1]);
                flag=1;
            }
            else if(mark[c[i]%n])
            {
                y=mark[c[i]%n];
                printf("%d\n",i-y);
                for(j=y+1;j<=i;j++) printf("%d\n",c[j]-c[j-1]);
                flag=1;
            }
            mark[c[i]%n]=i;
        }
    }

    return 0;
}

抱歉!评论已关闭.