poj 2356 简单的抽屉问题

Find a multiple
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 4790   Accepted: 2078   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

题目大意: 给出n个数,选出连续的若干m个数,使得和为n的倍数。输出m,以及任意顺序的m个数。
解题思路:用sum[i]表示第1~i个数的和对n取余的结果,那么共有n+1个数。而取余的结果为0~n-1, 相当于n个抽屉。根据抽屉原理,相当于至少有2个数在同一个抽屉中。
1>如果存在sum[i]==0,那么就是说明1~i的和恰好为n的倍数。
2>否则,一定存在两个值i, j(i<j)使得sum[i]==sum[j],那么i+1~j(a[i]----a[j-1])之间的数的和为n的倍数.由于要找两个相同的值,所以可以用一个数组pla[i]=j,表示模为i的值在j的位置。
#include <iostream>
#include<stdio.h>
using namespace std;
int main()
{
    int a[10005],n,i,j,k,t;
    __int64 sum[10005];
    while(scanf("%d",&n)!=EOF)
    {

        sum[0]=t=0;
        for(i=0;i<n;i++)
        {
            scanf("%d",&a[i]);
            sum[i+1]=sum[i]+a[i];
        }
        for(i=0;i<=n;i++)
            sum[i]=sum[i]%n;
        for(i=0;i<n;i++)
        {
            for(j=i+1;j<=n;j++)
            {
                if(sum[i]==sum[j])
                {
                    t=1;break;
                }
            }
            if(t==1) break;
        }
        if(n==1) printf("%d\n",a[0]);
        if(n>1)
        {
        printf("%d\n",j-i);
        for(k=i;k<j;k++)
            printf("%d\n",a[k]);
        }
    }
    return 0;
}
View Code

 


posted on 2013-07-10 15:27  _洋洋  阅读(160)  评论(0编辑  收藏  举报

导航