【连续子段和被某数整除】SOJ 2293: The Longest SubSequence

You will be given a sequence consists of many numbers, your task is to calculate the length of the longest consecutive subsequence , the sum of which can be divided by another given number.

Input
There are multiple test cases.
The first line of each case contains two integer N and M, (0< N <= 100000, 0 < M < 10000),then followed by a line consists of N integers a1,a2,...an,
( -100000000 <= a1,a2,...an <= 100000000 ).

Output
For each test case,Output the length of the longest consecutive subsequence , the sum of which can be divided by M.

Sample Input

2 3
1 6
3 3
2 3 6
2 5
1 3

Sample Output

1
2
0

 

题目重述:求长的连续子段使其子段和能被某数整除

分析:枚举所有子段和最坏情况要O(n^2)的时间 必然超时

考虑到若用一个sum求前n个数的和 sum%m的值如果在前面出现过 则说明这一段可以整除m 

因此用一个vis数组保存余数为x的出现下标 当vis[x]被访问过 则说明i-vis[x]这一段能被整除

 

代码如下

#include <cstring>
#include <cstdio>


const int maxN=100000+50;

int Sum;
int vis[maxN];
int main()
{
	int N,M,i,temp,id,ans;
	while(scanf("%d%d",&N,&M)==2)
	{
		memset(vis,-1,sizeof(vis));
		Sum=0;
		vis[0]=0;
		ans=0;
		for (i=1;i<=N;i++)
		{
			scanf("%d",&temp);
			Sum+=temp;
			id=Sum%M;
			if (id<0)
			{
				id+=M;
			}
			if (vis[id]==-1)
			{
				vis[id]=i;
			}
			else
			{
				temp=i-vis[id];
				if (ans<temp)
				{
					ans=temp;
				}
			}
		}
		printf("%d\n",ans);
	}
	return 0;
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值