jzoj3783-[NOIP2014模拟8.19]签到题【结论题】

正题

题目链接:https://jzoj.net/senior/#main/show/3783


题目大意

n n 个数,求这个序列中一个非空子集的和是 n n 的倍数。


解题思路

可以知道一定有一种解法是一段连续的序列。

证明:设 s x s_x 表示 ( i = 1 x a i ) % n (\sum_{i=1}^xa_i)\%n ,那么我们要找到一个 s l = s r s_l=s_r
若有 s i = 0 s_i=0 ,那么显然有答案
若没有 s i s_i 为0,那么在这 n n 个数中有 n 1 n-1 个可能的取值,那么就必定有一个 s l = s r s_l=s_r

证毕

然后 O ( n ) O(n) s i s_i 就好了。


c o d e code

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N=100010;
int T,n,a[N],sum,l,r,v[N*2];
int main()
{
	//freopen("checkin.in","r",stdin);
	//freopen("checkin.out","w",stdout);
	scanf("%d",&T);
	while(T--){
		scanf("%d",&n);
		memset(v,0,sizeof(v));
		sum=0;l=-1;r=-1;
		for(int i=1;i<=n;i++){
			scanf("%d",&a[i]);
			sum=(sum+a[i])%n;
			if(!sum){l=0;r=i;}
			if(v[sum+n]){l=v[sum+n];r=i;} 
			v[sum+n]=i;
		}
		if(l==-1){
			printf("-1\n");
			continue;
		}
		printf("%d\n",r-l);
		for(int i=l+1;i<=r;i++)
			printf("%d ",a[i]);
		putchar('\n');
	}
}
发布了867 篇原创文章 · 获赞 55 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/Mr_wuyongcong/article/details/103932029