Find a multiple

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).

·····

题目大意:先是一个n,再给你n个数,要你从这n个数中任选某一段数,这段数的和是n的倍数

首先用数组sum[i]表示从第1个数到第i个的和mod n,如果存在sum[i]==0,那么直接输出这i个数,否则则不存在sum[i]==0;

一共有n个sum[i],sum[i]==0,并且sum[i]<n,根据鸽巢原理,我们可以推断,在这n个sum[i]中,至少有两个sum[i]相等,找出这任意两个数,即可求得答案。

#include<iostream>
#include<set>
#include<map>
#include<cstring>
#include<cstdio>
using namespace std;
typedef long long ll;
ll a[100000];
ll sum[100000];
ll b[100000];
int main()
{
    ll n;
    cin>>n;
    memset(sum,0,sizeof(sum));
    memset(b,0,sizeof(b));
    for(ll i=1;i<=n;i++)
    {
        cin>>a[i];
        sum[i]=(sum[i-1]+a[i])%n;
    }
    for(ll i=1;i<=n;i++)
    {
        if(sum[i]==0)
        {
            cout<<i<<endl;
            for(int j=1;j<=i;j++)
                cout<<a[j]<<"\n";    
            break;
        }
        if(b[sum[i]]==0)
            b[sum[i]]=i;
        else
        {
            cout<<i-b[sum[i]]<<endl;
            for(ll j=b[sum[i]]+1;j<=i;j++)
                cout<<a[j]<<"\n";
            break;
        }
    }
    return 0;
}

这道题考察了对鸽巢原理的应用,也很巧妙。

以上。

猜你喜欢

转载自www.cnblogs.com/zjydeoneday/p/11361074.html