*[topcoder]GooseTattarrattatDiv1

http://community.topcoder.com/stat?c=problem_statement&pm=12730&rd=15701

这道题有点意思。首先把字符串变成回文,多个字符可能有交叉的等同关系,那么有些字符最终都要是要变成同一个。这个是可以用并查集来做的,标程怕并不是所有人都知道并查集,就用了图的DFS来做。这里用并查集的朴素版本来做,但x = comp[x];y = comp[y];这两句话必不可少,否则下面的循环过程中变化。

#include <string>
#include <vector>
using namespace std;

class GooseTattarrattatDiv1 {
public:
    int getmin(string S);
};

int GooseTattarrattatDiv1::getmin(string S) {
    vector<int> count(26);
    for (int i = 0; i < S.length(); i++) {
        count[S[i]-'a']++;
    }
    int len = S.length();
    vector<int> comp(26);
    for (int i = 0; i < 26; i++) {
        comp[i] = i;
    }
    for (int i = 0; i < len/2; i++) {
        int x = S[i] - 'a';
        int y = S[len - i - 1] - 'a';
        x = comp[x];
        y = comp[y];
        for (int c = 0; c < 26; c++) {
            if (comp[c] == x) {
                comp[c] = y;
            }
        }
    }
    int ans = 0;
    for (int i = 0; i < 26; i++) {
        int size = 0;
        int _max = 0;
        for (int c = 0; c < 26; c++) {
            if (comp[c] != i) continue;
            size += count[c];
            _max = max(count[c], _max);
        }
        ans += size - _max;
    }
    return ans;
};

  

posted @ 2013-11-30 01:47  阿牧遥  阅读(270)  评论(0编辑  收藏  举报