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.
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个数中找一段连续的和恰好为n的倍数的子序列,由于是求一个连续的子序列,所以可以用和数组来优化,只要在和数组中找到两数之差为n的倍数的两个点就可以了,但这样时间复杂度为O(n^2),所以对和数组中每一个数对n取模,这样在和数组中只要找到两个相等的数,用桶可以在O(n)的时间复杂度里完成,下面是程序:
#include<stdio.h>
#include<iostream>
using namespace std;
int t[10005],a[10005];
int main(){
int n,i,s=0;
scanf("%d",&n);
for(i=1;i<=n;i++){
scanf("%d",&a[i]);
s=(s+a[i])%n;
if(t[s]|!s){
break;
}
else{
t[s]=i;
}
}
printf("%d\n",i-t[s]);
for(t[s]++;t[s]<=i;t[s]++){
printf("%d\n",a[t[s]]);
}
return 0;
}
注意:要特别处理和数组取余后为0的情况(这个时候可以直接输出)