石子合併 BZOJ - 3229

題目傳送門

題意:石子合併問題一般來說都是O(N^3)的複雜度,如果用四邊形不等式優化的話可以使時間複雜度降低到O(N^2)的複雜度,但是這個題目的數據範圍是40000,所以這個題要用到GarsiaWachs算法,可以使時間複雜度降到O(N*logN),從而解決這個題目。

#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <list>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>

#define MAXN 50010
#define MAXE 40
#define INF 1e9
#define MOD 100003
#define LL long long
#define ULL unsigned long long
#define pi 3.14159

using namespace std;

int stone[MAXN];
int sum = 0;
int cnt = 1;

void combine(int k) {
    int temp = stone[k] + stone[k - 1];
    sum += temp;
    for (int i = k; i < cnt - 1; ++i) {
        stone[i] = stone[i + 1];
    }
    cnt--;
    int pos = k - 1;
    while (pos && stone[pos - 1] < temp) {
        stone[pos] = stone[pos - 1];
        pos--;
    }
    stone[pos] = temp;
    while (pos >= 2 && stone[pos] >= stone[pos - 2]) {
        int d = cnt - pos;
        combine(pos - 1);
        pos = cnt - d;
    }
}

int main() {
    std::ios::sync_with_stdio(false);
    int n;
    cin >> n;
    for (int i = 0; i < n; ++i) {
        cin >> stone[i];
    }
    for (int i = 1; i < n; ++i) {
        stone[cnt++] = stone[i];
        while (cnt >= 3 && stone[cnt - 3] <= stone[cnt - 1]) {
            combine(cnt - 2);
        }
    }
    while(cnt > 1)
        combine(cnt - 1);
    cout << sum << endl;
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章