一个长度为N的数组A,从A中选出若干个数,使得这些数的和是N的倍数。
例如:N = 8,数组A包括:2 5 6 3 18 7 11 19,可以选2 6,因为2 + 6 = 8,是8的倍数。
Input
第1行:1个数N,N为数组的长度,同时也是要求的倍数。(2 <= N <= 50000)
第2 - N + 1行:数组A的元素。(0 < A[i] <= 10^9)
Output
如果没有符合条件的组合,输出No Solution。
第1行:1个数S表示你所选择的数的数量。
第2 - S + 1行:每行1个数,对应你所选择的数。
Input示例
8
2
5
6
3
18
7
11
19
Output示例
2
2
6
思路:
计算N个数的前缀和,前缀和模N的种类最多N个,所以其中必有一个前缀和模N为0,或者有两个前缀和模N的值相等,如果相等,则这两个前缀和的差必定是N的倍数。
#include <iostream>
#include <cstring>
using namespace std;
const int MAXN = 50005;
typedef long long int ll;
ll sum[MAXN];
ll n;
int pos[MAXN];
ll a[MAXN];
int main()
{
cin >> n;
memset(pos, 0, sizeof(pos));
memset(sum, 0, sizeof(sum));
a[0] = 0;
int l, r;
for (int i = 1; i <= n; i++)
{
cin >> a[i];
}
for (int i = 1; i <= n; i++)
{
sum[i] = (sum[i-1] + a[i]) % n;
if (sum[i] == 0)
{
l = 1;
r = i;
break;
}
else if (pos[sum[i]] != 0)
{
l = pos[sum[i]] + 1;
r = i;
break;
}
pos[sum[i]] = i;
}
cout << r - l + 1 << endl;
for(int i = l;i <= r;i++)
{
cout << a[i] << endl;
}
return 0;
}