【POJ 2356】Find a multiple(抽屉原理-好题)

来源:互联网 发布:淘宝店铺怎么查排名 编辑:程序博客网 时间:2024/05/18 01:22



点击打开题目


Find a multiple
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 8263 Accepted: 3592 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

512341

Sample Output

223

Source

Ural Collegiate Programming Contest 1999

题意:第一行是数字n第二行是数组n的长度,接下来是数组元素,求在数组元素中存在连续的元素之和是n的倍数,输出元素个数和每个元素的值

题解:利用前缀和抽屉原理,本题一定有解。

证:数字n,有n个元素的数组,可以得到n个前缀和,每个前缀和对n求余则必定在【1~n-1】内,由抽屉原理,则至少有两个前缀和对n的余数相同,假 设为c,v;

则,能整除n的数字即为 v-c 之间的数字,输出其对应下标即可



代码:


#include<iostream>#include<algorithm>#include<cstring>using namespace std;int a[10010];int mod[10010];int sum[10010];int main(){int n;while(cin>>n){memset(a,0,sizeof(a));//存元素个数memset(mod,0,sizeof(mod));//存余数memset(sum,0,sizeof(sum));//存前缀和for(int i=1;i<=n;i++)cin>>a[i];for(int i=1;i<=n;i++){sum[i]=sum[i-1]+a[i];if(sum[i]%n==0){cout<<i<<endl;for(int j=1;j<=i;j++){cout<<a[j]<<endl;}break;}else if(mod[sum[i]%n]!=0){cout<<i-mod[sum[i]%n]<<endl;for(int j=mod[sum[i]%n]+1;j<=i;j++)cout<<a[j]<<endl;break;}mod[sum[i]%n]=i;//记录该前缀和的余数是否出现过}}return 0;}



原创粉丝点击