a420中等骰子模擬・以三個朝向重建六面

APCS 2020/07:骰子 (ZeroJudge f580)

保存上、前、右三面的點數,依操作同步更新或交換整顆骰子。

前往題目練習 →回報教學錯誤時間 O(n+m);空間 O(n)。

這題在學什麼

對面點數和為 7,因此只要記錄 (top,front,right),就能得到下、後、左為 (7−top,7−front,7−right)。初始狀態為 (1,4,2)。正數操作要交換這整組狀態,因為位置交換連骰子的朝向一起交換。

向前滾時,後面來到上面、上面移到前面,所以新狀態為 (7−front,top,right)。向右滾時,左面來到上面、上面移到右面,所以新狀態為 (7−right,front,top)。每個式子都從同一份舊值計算,才能避免先更新 top 後誤用新 top。

Step-by-step animation

公開第二例:三顆骰子的上、前、右

回報動畫錯誤
步驟 1 / 4

三顆初始朝向

每個位置都從 (1,4,2) 開始。

1:(1,4,2)
2:(1,4,2)
3:(1,4,2)
朝向格式
(上,前,右)

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
int main() {
    ios::sync_with_stdio(false); cin.tie(nullptr);
    int n,m; cin >> n >> m;
    vector<array<int,3>> dice(n,{1,4,2});
    for (int i=0;i<m;i++) {
        int a,b; cin >> a >> b; --a;
        if (b>0) {
            swap(dice[a],dice[b-1]);
        } else {
            auto [top,front,right]=dice[a];
            if (b==-1) dice[a]={7-front,top,right};
            else dice[a]={7-right,front,top};
        }
    }
    for (int i=0;i<n;i++) cout << dice[i][0] << (i+1==n?'\n':' ');
}

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

更多