题意:给定n个数,从中选出连续的若干个,使得和为n的倍数。多解时输出任意解。
分析:设sum[0]=0,sum[i]表示数列中第1~i个数的和对n取余的结果。那么现在有sum[0~n],n + 1个整数,分布在区间[0, n-1]上的n个整数点上,则至少有两个数会分布在同一个整数点,即存在sum[i]==sum[j]且i!=j。这样以来第i+1~j个数即为所求。
View Code
#include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> using namespace std; #define maxn 10005 int n; int f[maxn]; int sum[maxn]; int pos[maxn]; void input() { scanf("%d", &n); for (int i = 1; i <= n; i++) scanf("%d", &f[i]); sum[0] = f[0] = 0; for (int i = 1; i <= n; i++) sum[i] = (sum[i - 1] + f[i]) % n; } void work() { memset(pos, -1, sizeof(pos)); pos[0] = 0; for (int i = 1; i <= n; i++) if (pos[sum[i]] == -1) pos[sum[i]] = i; else { printf("%d\n", i - pos[sum[i]]); for (int j = pos[sum[i]] + 1; j <= i; j++) printf("%d\n", f[j]); return; } } int main() { //freopen("t.txt", "r", stdin); input(); work(); return 0; }