C♯の勉強

C♯4.0 で TopCoder の過去問を解きます。

TopCoder SRM 589: GooseTattarrattatDiv1

問題文

ToLookup() が使えないことから微妙なプログラムになってしまった。

public class GooseTattarrattatDiv1 {
    public int getmin(string S) {
        int n = S.Length;
        DisjointSet ds = new DisjointSet(26);
        for (int i = 0; i < n; i++)
        {
            ds.unionSet(S[i] - 'a', S[n - 1 - i] - 'a');
        }
        var histogram = new int[26];
        foreach(var c in S) histogram[c-'a']++;

        return Enumerable.Range(0, 26)
            .Where(index => index == ds.root(index))
            .Select(index => Enumerable.Range(0, 26).Where(j => index == ds.root(j)).ToArray())
            .Select(g => g.Sum(index => histogram[index]) - g.Max(index => histogram[index]))
            .Sum();
    }
}