a694簡單手指狀態的0→1轉換計數

CPE:Eb Alto Saxophone Player (UVa 10415)

按鍵持續按住不重計,只計新音符新增的按鍵。

前往題目練習 →回報教學錯誤歌長L,時間 O(10L),固定十根手指空間 O(1)。

解題思路

為14種音符建立所需手指集合,維護前一音符的按住狀態 previous。演奏下一音符 current 時,只有 current 中存在而 previous 不存在的手指才增加一次計數;集合差 current−previous 就是本次新按下的手指。

更新計數後直接將 previous 換成 current,所以不需要分別模擬抬起動作。每首歌從空集合重新開始。題目允許空歌行,必須逐行讀且不能跳過空行,空歌的十個計數都是0。依手指1至10輸出十個整數,中間單一空白。

Step-by-step animation

示意:歌曲 bCb

回報動畫錯誤
步驟 1 / 3

b

b需要手指2,第一次按下。

指2:按住
指3:鬆開
指2次數
1
指3次數
0

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <string>
#include <vector>
#include <array>
using namespace std;
int main() {
    string notes = "cdefgabCDEFGAB";
    vector<vector<int>> fingers = {{2, 3, 4, 7, 8, 9, 10},
                                   {2, 3, 4, 7, 8, 9},
                                   {2, 3, 4, 7, 8},
                                   {2, 3, 4, 7},
                                   {2, 3, 4},
                                   {2, 3},
                                   {2},
                                   {3},
                                   {1, 2, 3, 4, 7, 8, 9},
                                   {1, 2, 3, 4, 7, 8},
                                   {1, 2, 3, 4, 7},
                                   {1, 2, 3, 4},
                                   {1, 2, 3},
                                   {1, 2}};
    int tests;
    cin >> tests;
    string song;
    getline(cin, song);
    while (tests--) {
        getline(cin, song);
        array<int, 11> count{}, previous{};
        for (char note : song) {
            auto at = notes.find(note);
            if (at == string::npos)
                continue;
            array<int, 11> current{};
            for (int f : fingers[at])
                current[f] = 1;
            for (int f = 1; f <= 10; f++)
                if (current[f] && !previous[f])
                    count[f]++;
            previous = current;
        }
        for (int f = 1; f <= 10; f++)
            cout << (f == 1 ? "" : " ") << count[f];
        cout << '\n';
    }
}

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

更多