【POJ】2356-Find a multiple-鸽巢原理

Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 9080   Accepted: 3896   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

Ural Collegiate Programming Contest 1999

题目大意:给出n,紧接着给出n个数,要求出这n个数中的相加能被n整出的数,随便几个都是可以的,当然也可能有多种情况,只输出一种即可

思路:

典型的抽屉原理。

Sum[i]为序列中前i项的和。则有两种可能:

1.若有Sum[i]是N的倍数,则直接输出前i项。

2.如果没有任何的Sum[i]是N的倍数,则计算ri = Sum[i] % N。根据鸽巢原理,肯

定有Sum[i] % N == Sum[j] % N,i != j。则第 j 到第 i 项数的和即为N的倍数。

代码1:

#include<iostream>
#include<cstdio>
#include<cstring>
#define maxn 10010
using namespace std;

int a[maxn],sum[maxn]={0};
int main()
{
    int n;
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        cin>>a[i];
        sum[i]=(sum[i-1]+a[i])%n;
    }
    int flag=0;
    for(int i=1;i<=n;i++)
    {
        if(sum[i]%n==0)
        {
            cout<<i<<endl;
            for(int j=1;j<=i;j++)
                cout<<a[j]<<endl;
            flag=1;
            break;
        }
        else
        {
            for(int j=1;j<i;j++)
                if(sum[j]==sum[i])
                {
                    cout<<i-j<<endl;
                    for(int k=j+1;k<=i;k++)
                        cout<<a[k]<<endl;
                    flag=1;
                    break;
                }
        }
        if(flag) break;
    }
    return 0;
}

改进后的代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#define maxn 10010
using namespace std;

int vis[maxn],a[maxn],sum[maxn];
int main()
{
    int n;
    cin>>n;
    int st,en;
    memset(vis,-1,sizeof(vis));
    vis[0]=0;
    for(int i=1;i<=n;i++)
    {
        cin>>a[i];
        sum[i]=(sum[i-1]+a[i])%n;
        if(vis[sum[i]]==-1)
        {
            vis[sum[i]]=i;
        }
        else
        {
            st=vis[sum[i]];
            en=i;
        }
    }
    cout<<en-st<<endl;
    for(int i=st+1;i<=en;i++)
        cout<<a[i]<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/wentong_Xu/article/details/81672708