Find a multiple
Time Limit: 1000MS | Memory Limit: 65536K | |||
Total Submissions: 7418 | Accepted: 3233 | 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.
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个大于0不大于n的整数,判断是否存在其中的一段连续的数的和是n的倍数。
根据抽屉原理,不可能存在输出 0 的情况,证明如下:
用一个数组 sum[] 记录从 num[ 1 ] + num [ 2 ] + ... + num [ i ] 的值。
把每一个 sum 都对 n 求余,最后有 n 个余数,范围是 1 ~ n - 1 ,所以肯定至少有两个余数相等。证明完毕。
下面是搜解的过程:
用vector记录余数的个数与位置。
sum [ endd ] - sum [ st ] 对 n 求余是0,也就是说:sum [ st + 1 ] + sum [ st + 2 ] + ,,, + sum [ endd ] 是n的倍数。
从num [ st + 1 ] 输出到 num [ endd ] 即可。
新学的容器,可以记录相同的数先后出现的序号,从数组下标0开始存数,向后依次记下他们的序号。
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
int n;
int a[10010];
int sum[10010]={0};
int st,ed; //记录开始时间和结束时间
while(~scanf("%d",&n))
{
vector<int> pos[10010];
sum[0]=0;
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
sum[i]=sum[i-1]+a[i];
pos[sum[i]%n].push_back(i); //记录余数相等的和的序号
}
if(pos[0].size()>0) //存在前几个数的和是n的整数倍,直接输出前几个数
{
st=1; //开始是1
ed=pos[0][0]; //结束是第一个和是n整数倍的数
printf("%d\n",ed);
for(int i=1;i<=ed;i++)
printf("%d\n",a[i]);
}
else
{
for(int i=1;i<=n;i++)
{
if(pos[i].size()>1) //两个数对n取余数相等即 pos[i].size()>1
{
st=pos[i][0]+1; //开始位置定在第一个数的后一位
ed=pos[1][1]; //这中间从st到ed的和一定是n的倍数
printf("%d\n",ed-st+1);
for(int i=st;i<=ed;i++)
printf("%d\n",a[i]);
}
}
}
}
return 0;
}