hihocoder 1796 : 完美K倍子数组

#1796 : 完美K倍子数组

时间限制:10000ms

单点时限:1000ms

内存限制:256MB

描述

如果一个数组满足长度至少是2,并且其中任意两个不同的元素Ai和Aj (i ≠ j)其和Ai+Aj都是K的倍数,我们就称该数组是 完美K倍数组。  

现在给定一个包含N个整数的数组A = [A1, A2, ... AN]以及一个整数K,请你找出A的最长的完美子数组B,输出B的长度。  

如果这样的子数组不存在,输出-1。

输入

第一行包含两个整数N和K。  

第二行包含N个整数A1, A2, ... AN。  

1 ≤ N ≤ 100000  

1 ≤ Ai, K ≤ 1000000000

输出

一个整数,表示答案。

样例输入

5 3  
1 3 2 3 6

样例输出

3
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <set>
using namespace std;
int a[100000+500]; 
int main(int argc, char const *argv[])
{
	int n, k;
	cin>>n>>k;
	set<int> s;
	int flag = 0;
	for(int i = 0; i < n; i++)
		cin>>a[i];
	int ans_1 = 0, ans_2 = 0;
	for(int i = 0; i < n; i++)
	{
		if(a[i] % k == 0) ans_1++;
		else if(a[i] % k == k / 2) ans_2++;
		else {
			int tmp = a[i] % k;
			if(s.find(k - tmp) != s.end())//能找到 
				flag = 1;//标记是否个数两个,能够满足条件 
			s.insert(tmp);
		}
	}
	if(k % 2 != 0) ans_2 = 0;//不是偶数,统计不需要 
	int ans = max(ans_1, ans_2);
	if(flag && ans <= 1) cout<<2<<endl;
	else if(ans <= 1) cout<<-1<<endl;
	else cout<<ans<<endl;
    return 0;
}
原创文章 93 获赞 353 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weixin_43906799/article/details/105886460