a665簡單Hamming 距離按欄獨立最佳化

CPE:DNA Consensus String (UVa 1368)

每個位置選最多數字元,同票依字典序決定。

前往題目練習 →回報教學錯誤時間 O(mn),儲存字串時空間 O(mn)。

解題思路

總 Hamming 距離可以按位置分開相加。若第 j 欄選字元 c,該欄的代價為 m−count[j][c]。所以每欄獨立選出現最多的字元,就能讓所有欄的代價總和最小,完全不必枚舉 4^n 個候選字串。

同票時按 A,C,G,T 的順序檢查,只在次數嚴格更多時更新最佳字元,便保留最小字典序。各欄都採最小的最佳字元,也使整串在所有最優解中字典序最小。每筆輸出代表字串,下一行輸出各欄 m−最高次數之和,沒有額外案例標籤。

Step-by-step animation

示意:ACGT、ACGA、TCGT、TCGA

回報動畫錯誤
步驟 1 / 3

第一欄

A、T 各兩次,選 A,代價 2。

A:2
C:0
G:0
T:2
前綴
A
距離
2

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main() {
    int t;
    cin >> t;
    string alphabet = "ACGT";
    while (t--) {
        int m, n;
        cin >> m >> n;
        vector<string> a(m);
        for (auto &s : a)
            cin >> s;
        string answer;
        int distance = 0;
        for (int j = 0; j < n; j++) {
            int count[4] = {};
            for (auto &s : a)
                count[alphabet.find(s[j])]++;
            int best = 0;
            for (int c = 1; c < 4; c++)
                if (count[c] > count[best])
                    best = c;
            answer += alphabet[best];
            distance += m - count[best];
        }
        cout << answer << '\n' << distance << '\n';
    }
}

先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。

更多