Hatena::Grouptopcoder

TopCoderの問題を解く

解いた問題の一覧表

2009-05-23

MergeSort

| 16:47

問題文

548.28->886.11->890.45->962.99/1000

マージソートを行う際に必要な比較回数を数える。

class MergeSort {
public:
    int howManyComparisons(vector <int> numbers) {
        count = 0;
        const int sz = numbers.size();
        vector<long long> nums(sz);
        for (int i = 0; i < sz; i++)
            nums[i] = numbers[i];
        mergeSort(nums, 0, sz);
        return count;
    }
private:
    int count;
    const static long long INF = INT_MAX + 1ll;
    void merge(vector<long long>& A,
            const int p, const int q, const int r) {
        const int n1 = q - p;
        const int n2 = r - q;
        vector<long long> L(n1+1), R(n2+1);
        for (int i = 0; i < n1; i++)
            L[i] = A[p+i];
        for (int j = 0; j < n2; j++)
            R[j] = A[q+j];
        L[n1] = R[n2] = INF;
        int i = 0, j = 0;
        for (int k = p; k < r; k++) {
            if (L[i] != INF && R[j] != INF)
                count++;
            if (L[i] < R[j]) {
                A[k] = L[i];
                i++;
            } else if (L[i] > R[j]) {
                A[k] = R[j];
                j++;
            } else {
                A[k] = L[i]; k++;
                A[k] = R[j];
                i++; j++;
            }
        }
    }
    void mergeSort(vector<long long>& A, const int p, const int r) {
        if (r-p > 1) {
            const int q = (p+r) / 2;
            mergeSort(A, p, q);
            mergeSort(A, q, r);
            merge(A, p, q, r);
        }
    }
};