Codeforces Round #708 (Div. 2)B. M-arrays

8 篇文章 0 订阅

B. M-arrays

time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output

题目描述

You are given an array a1,a2,…,an consisting of n positive integers and a positive integer m.

You should divide elements of this array into some arrays. You can order the elements in the new arrays as you want.

Let’s call an array m-divisible if for each two adjacent numbers in the array (two numbers on the positions i and i+1 are called adjacent for each i) their sum is divisible by m. An array of one element is m-divisible.

Find the smallest number of m-divisible arrays that a1,a2,…,an is possible to divide into.

您将得到一个数组a1,a2,…,an它由n个正整数和一个正整数m组成。 您应该将此数组的元素划分为一些数组。您可以根据需要对新数组中的元素进行排序。 如果对数组中的每个相邻两个数字(位置ii和i + 1上的两个数字每个i相邻),它们的总和可以被m整除,那么我们将其称为m可分割的数组。一个元素的数组可以被m整除。 找到a1,a2,…,an可以划分的最小的m可整除数组。

Input

The first line contains a single integer t (1≤t≤1000) — the number of test cases.

The first line of each test case contains two integers n, m (1≤n≤105,1≤m≤105).

The second line of each test case contains n integers a1,a2,…,an (1≤ai≤109).

It is guaranteed that the sum of n and the sum of m over all test cases do not exceed 10^5.

第一行包含一个整数t(1≤t≤1000)(1≤t≤1000)-测试用例数。 每个测试用例的第一行包含两个整数n,m(1≤n≤105,1≤m≤105)。
每个测试用例的第二行包含n个整数a1,a2,…,an(1≤ai≤109)。 确保所有测试用例的nn和mm的总和不超过105

Output

For each test case print the answer to the problem.

Example

inputCopy

4
6 4
2 2 8 6 9 4
10 8
1 1 1 5 2 4 4 8 6 7
1 1
666
2 2
2 4

outputCopy

3
6
1
1

Note
In the first test case we can divide the elements as follows:

[4,8]. It is a 4-divisible array because 4+8 is divisible by 4.
[2,6,2]. It is a 4-divisible array because 2+6 and 6+2 are divisible by 4.
[9]. It is a 4-divisible array because it consists of one element.

解题思路

关键词:构造算法、贪心算术

题目讲述的时根据 m 的值然后给数组进行可整除分组,我们的想法就是

  1. 将能被 m 整除的一组;
  2. 其他就是的余数就是 1,2,3,…,m-2,m-1;
  3. 我们就将前后的组合在一起,两边往中间靠,1和m-1, 2和m-2,最后两个能形成对,或者还剩1个都能组成一组;注意余数剩(1和m-1)或其他组合的个数要大于一,避免出现 0+0<=1,这是不能成组的
  4. 但是当 abs(p-q)>1 时,就会形成 abs(p-q) 组;

参考代码

#include<iostream>
#include<cmath>
using namespace std;

int main()
{
	int t,n,m,p,q;
	cin>>t;
	
	while(t--){
		cin>>n>>m;
		int b[100001]={0};
		
		for(int i=0;i<n;i++){
			cin>>p;
			b[p%m]++;//用来标记余数的个数
		}
		int num=0;
		if(b[0]>0)
			num++; //余数为0的形成一组
		
		for(int i=1;i<=m/2;i++){
			p=b[i];
			q=b[m-i]; //余数互补的一组,多出来的各一组
			if( abs(p-q)<=1 && p+q>0) //注意一定要判断p+q>0,避免出现0+0<=1
				num++;
			else
				num+=abs(p-q);
		}
		cout<<num<<endl;
	}
	return 0;
}

没明白的话,欢迎来打扰;
学会了的话,留下一个赞,互相鼓励哦!!!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值