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;
}

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

以上。

转载于:https://www.cnblogs.com/zjydeoneday/p/11361074.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值