Divisiblity of Differences
You are given a multiset of n integers. You should select exactly k of them in a such way that the difference between any two of them is divisible by m, or tell that it is impossible.
Numbers can be repeated in the original multiset and in the multiset of selected numbers, but number of occurrences of any number in multiset of selected numbers should not exceed the number of its occurrences in the original multiset.
Input
First line contains three integers n, k and m (2 ≤ k ≤ n ≤ 100 000, 1 ≤ m ≤ 100 000) — number of integers in the multiset, number of integers you should select and the required divisor of any pair of selected integers.
Second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 109) — the numbers in the multiset.
OutputIf it is not possible to select k numbers in the desired way, output «No» (without the quotes).
Otherwise, in the first line of output print «Yes» (without the quotes). In the second line print k integers b1, b2, ..., bk — the selected numbers. If there are multiple possible solutions, print any of them.
Examples3 2 3 1 8 4
Yes 1 4
3 3 3 1 8 4
No
4 3 5 2 7 7 7
Yes 2 7 7
【题意】:给你n个数a[i],让你找出一个大小为k的集合,使得集合中的数两两之差为m的倍数。 若有多解,输出任意一个集合即可。 【分析】:若一个集合中的数,两两之差为m的倍数,则他们 mod m 的值均相等。所以O(N)扫一遍,对于每个数a:vector v[a%m].push_back(a) 一旦有一个集合大小为k,则输出。
code
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn = 1e6+10;
int main(){
int n,k,m;
cin >> n >> k >> m;
int arr[maxn] = {0};
int val[maxn];
for(int i = 0; i < n; i++){
cin >> val[i];
arr[val[i]%m]++;
}
int pos = -1;
for(int i = 0; i < m; i++){
if(arr[i] >= k){
pos = i;
break;
}
}
if(pos == -1){
cout << "No" << endl;
}
else{
cout << "Yes" << endl;
int i = 0;
while(k--){
while(val[i] % m != pos){
i++;
}
cout << val[i] << " ";
i++;
}
cout << endl;
}
return 0;
}
本文介绍了一个关于从多集中选择特定数量的整数,使这些整数两两之间的差值都是给定数值的倍数的问题。通过分析可知,只有当所有选中整数对给定数值取模结果相同时才能满足条件。文章给出了一个有效的算法实现,通过遍历多集并统计各数模结果的频次来快速判断是否存在符合条件的解。
309

被折叠的 条评论
为什么被折叠?



