a484中等按大小排序後的顏色區段貪心

CPE:Building designing (UVa 11039)

每個連續同色區段選一層,得到最長交替樓層。

前往題目練習 →回報教學錯誤每筆時間 O(n log n),空間 O(n)。

解題思路

可重新排列,且大小互異,所以先按絕對值由小到大排列,這正是由頂至底的唯一大小順序。忽略大小後只剩紅藍序列;連續同色的一段最多只能選一層,因為同段之間不存在另一色可插入。

每個同色區段選第一層就能與下一段銜接,且段與段的大小已嚴格增加,因此區段數就是最優層數。掃描排序結果,顏色改變就加1。N可達50萬,必須排序後一次掃描,不能做O(N²)最長子序列。

Step-by-step animation

示意:7、−2、6、9、−3

回報動畫錯誤
步驟 1 / 3

按大小排序

由小到大為−2、−3、6、7、9。

−2紅
−3紅
6藍
7藍
9藍
樓層數
5

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <vector>
#include <algorithm>
#include <cstdlib>
using namespace std;
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int T;
    cin >> T;
    while (T--) {
        int n;
        cin >> n;
        vector<int> a(n);
        for (int &x : a)
            cin >> x;
        sort(a.begin(), a.end(), [](int x, int y) { return abs(x) < abs(y); });
        int answer = 0, previous = 0;
        for (int x : a) {
            int color = (x > 0 ? 1 : -1);
            if (color != previous) {
                ++answer;
                previous = color;
            }
        }
        cout << answer << '\n';
    }
}

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

更多