51nod 1103:N的倍数 抽屉原理

题目来源: Ural 1302
基准时间限制:1 秒 空间限制:131072 KB 分值: 40 难度:4级算法题
51nod 1103:N的倍数 抽屉原理 收藏
51nod 1103:N的倍数 抽屉原理 关注
一个长度为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的时候,要想到抽屉原理。

代码:

#include <iostream>
#include <algorithm>
#include <cmath>
#include <vector>
#include <string>
#include <cstring>
#pragma warning(disable:4996)
using namespace std; long long a[50005];
long long sum[50005];
long long pos[50005];
long long n; int main()
{
int i, j, flag = 0;
cin >> n; memset(sum, 0, sizeof(sum)); for (i = 1; i <= n; i++)
{
cin >> a[i];
if (flag == 1)
{
continue;
}
else
{
sum[i] = (sum[i - 1] + a[i]) % n;
if (sum[i] == 0)
{
flag = 1;
cout << i << endl;
for (j = 1; j <= i; j++)
{
cout << a[j] << endl;
}
continue;
}
if (pos[sum[i]] == 0)
{
pos[sum[i]] = i;
}
else
{
flag = 1;
cout << i - pos[sum[i]] << endl;
for (j = pos[sum[i]]+1; j <= i; j++)
{
cout << a[j] << endl;
}
}
}
}
return 0;
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

上一篇:51nod——T1103 N的倍数


下一篇:51nod-1103-抽屉原理