题目链接
https://codeforces.com/contest/1492/problem/E
题意
给定 个长度为 的正整数array,其中
问是否存在一个array,使得这个array 与 其他每个array的difference(不同元素的个数) ?
题解
暴搜,我们可以先令 等于第一个array,然后看一下其他array中,有没有 的,如果有,尝试更改 中的一个元素,更改后再看一下其他array的difference情况,如果还是不行,就继续尝试更改其他元素。
直到所有array的
注意到,因为基于第一个array,所以最多只能更改两个元素,我们可以给在搜索的时候设置一个深度 left
,代表还可以更改几个元素。一开始就是dfs(2)
。
注1: 本题时限卡的比较紧,时限为2s,我们可以设定2s内如果搜索不出结果就直接返回"No”。
copy
1 2 3 4 5 6
| double start = clock(); double passed = clock() - start; if (passed > 1950.0) { cout << "No" << "\n" exit(0); }
|
注2: 暴搜的时候记得回溯!
代码
copy
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
| #include <bits/stdc++.h> using namespace std; int n,m; vector< vector<int> > arr; vector<int> ans; vector<int> cnt; double start; inline bool check() { for (int i = 0; i < n; i++) { if (cnt[i] > 2) return 0; } return 1; } void dfs(int left) { if (left < 0) return; if (clock()-start > 1950) { printf("No\n"); exit(0); } for (int i = 0; i < n; i++) { cnt[i] = 0; vector<int> pos; for (int j = 0; j < m; j++) { if (ans[j] != arr[i][j]) { cnt[i] += 1; pos.push_back(j); } } if (cnt[i]-left > 2) { return; } if (cnt[i] > 2) { for (int j : pos) { int pre = ans[j]; ans[j] = arr[i][j]; dfs(left-1); ans[j] = pre; } } } if (check()) { printf("Yes\n"); for (int j = 0; j < m; j++) printf("%d ", ans[j]); printf("\n"); exit(0); } } int main() { scanf("%d%d",&n,&m); start = clock(); arr = vector<vector<int> > (n, vector<int>(m,0)); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { scanf("%d", &arr[i][j]); } } ans = arr[0]; cnt = vector<int>(n,0); dfs(2); printf("No\n"); }
|
Author
tom0727
LastMod
2025-05-01
(d141563)
,更新历史
License
CC BY-SA 4.0