题意
有n个朋友,1到m天每天要选一个朋友,要求任意一个朋友被选择的天数不能大于 ⌈𝑚 / 2⌉
思路
每一天先任意地选择一个朋友,则至多会有一个朋友被选择的天数大于 ⌈𝑚 / 2⌉
,对于该朋友,我们只要在选择该朋友的那一天的选择其他朋友,直到选择该朋友的天数不大于⌈𝑚 / 2⌉
,如果超过⌈𝑚 / 2⌉
的天数只能选择该朋友,则输出NO
代码
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <set>
#include <stack>
#include <queue>
using namespace std;
using pii = pair<int, int>;
const int N = 1e5 + 10;
// n: the count of friends
// m: the count of days
int n, m;
int res[N]; // 记录每天选择的朋友
int cnt[N]; // 记录朋友被选择的天数
void solve() {
cin >> n >> m;
for(int i = 1; i <= n; i++) cnt[i] = 0;
vector<vector<int> > g(m + 1);
for(int i = 1; i <= m; i++) {
int k;
cin >> k;
for(int j = 0; j < k; j++) {
int x;
cin >> x;
g[i].push_back(x);
// 每次先选择第一个朋友
if(j == 0) {
res[i] = x;
cnt[x]++;
}
}
}
int idx = -1;
for(int i = 1; i <= n; i++)
if(cnt[i] > (m + 1) / 2)
idx = i;
// cout << idx << ' ' << cnt[idx] << endl;
// 满足条件
if(idx == -1) {
cout << "YES\n";
for(int i = 1; i <= m; i++)
cout << res[i] << ' ';
cout << endl;
return ;
}
for(int i = 1; i <= m && cnt[idx] > (m + 1) / 2; i++) {
// 如果有其他朋友可以选择,替换他
if(res[i] == idx && g[i].size() > 1) {
int y = g[i].back();
res[i] = y;
cnt[y]++;
cnt[idx]--;
}
}
if(cnt[idx] > (m + 1) / 2) cout << "NO\n";
else {
cout << "YES\n";
for(int i = 1; i <= m; i++)
cout << res[i] << ' ';
cout << endl;
}
}
int main() {
// freopen("in.txt", "r", stdin);
int t;
cin >> t;
while(t--) solve();
return 0;
}