POJ 2356 find multiple
题意:
输入一个正整数 N ,接着输入 N 和 正整数 nums[1], nums[2], ... ... , nums[N],
试问可否从这 N 个正整数中找出一组连续的数,它们的和能被 N 整除。
思路:
鸽巢原理,构造一个序列 sums[1] = nums[1], sums[2] = nums[1] + nums[2], ... ...
sums[N] = nums[1] + nums[2] + ... ...+ nums[N]
则 sums[1] < sums[2] < ... ... < sums[N]
此时有两种情况:
1.这 N 个 sums 中存在一个 sums[X] 能被 N 整除
2.这 N 个 sums 中没有一个能被 N 整除,则它们与 N 的余数必然在 [ 1, N - 1 ] 中,
构造 N - 1 个抽屉,其中必然有两个 sums[K], sums[L] 在一个抽屉中
即 sums[K] ≡ sums[L] mod N,所以 sums[L] - sums[K] =
nums[K + 1] + nums[K + 2] + ... ... nums[L] ≡ 0 mod 3.
#include <iostream>
#include <vector>
#include <string.h>
using namespace std;
#define MAX_SIZE 10005
int nums[MAX_SIZE];
int sums[MAX_SIZE];
vector< int > count_vector[MAX_SIZE];
int main()
{
sums[0] = 0;
int ans_len = -1, ans_start, ans_end;
int limit_num;
cin >> limit_num;
for( int i = 1; i <= limit_num; ++i ){
cin >> nums[i];
sums[i] = nums[i] + sums[i - 1];
sums[i - 1] = sums[i - 1] % limit_num;
}
sums[limit_num] = sums[limit_num] % limit_num;
for( int i = 1; i <= limit_num; ++i ){
if( sums[i] == 0 ){
ans_len = i;
ans_start = 1;
ans_end = i;
break;
}
}
if( ans_len == -1 ){
for( int i = 1; i <= limit_num; ++i ){
int index = sums[i];
count_vector[index].push_back( i );
if( count_vector[index].size() > 1 ){
ans_start = count_vector[index][0] + 1;
ans_end = count_vector[index][1];
ans_len = ans_end - ans_start + 1;
}
}
}
cout << ans_len << '\n';
for( int i = ans_start; i <= ans_end; ++i ){
cout << nums[i] << '\n';
}
return 0;
}