#cpp
#字符串
#数组
题目描述
题解
方法:按列统计
思路
- 统计第一列每个字符的数量记到
int cnt[26]
中 - 找到数量最多的字符(如果存在相同的,取字典序小的),数量记为
maxCnt
,该字符就是最优字符。 m-maxCnt
即为该列的汉明距离- 对其他列也按上述方法统计,所有列的汉明距离之和即为结果
代码
#include<bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while(t--) {
int m, n;
cin >> m >> n;
vector<string> dna(m);
// 输入dna序列
for (int i = 0; i < m; i++) {
cin >> dna[i];
}
string ans;
int ce = 0; // 保存 “consensus error”
// 统计每列出现频率最高的字符
for (int i = 0; i < n; i++) {
int cnt[26] = {0};
// 统计该列各个字符的数量
for (int j = 0; j < m; j++) {
cnt[dna[j][i] - 'A']++;
}
// 找到出现最多的字符
int idx = 0;
for (int i = 0; i < 26; i++) {
if (cnt[i] > cnt[idx]) {
idx = i;
}
}
// 累计差异
ce += m - cnt[idx];
// 追加该列出现最多的字符
ans.push_back((char)(idx + 'A'));
}
cout << ans << '\n' << ce << '\n';
}
return 0;
}
复杂度分析
- 时间复杂度: O ( m n ) O(mn) O(mn)。
- 空间复杂度: O ( m n ) O(mn) O(mn)。