b105困難

106 北二區資訊學科能力競賽(2017)|磁磚問題

保持原磁磚格線並重用外邊餘料。

解題思路

N=aL+r、M=bL+s。內部ab塊完整磁磚一定需要;外圈另需a塊L×s邊條、b塊r×L邊條,以及r,s都非0時的一塊r×s角料。

邊條有一邊長L,放在同一片新磚中的邊條必須互相平行;旋轉後可視為寬s與寬r的滿長條,總寬不超過L。一片取i、j條後,剩餘寬L−is−jr,若至少min(r,s),角料可旋轉放入。

DP狀態為已供應兩種邊條數與角料是否完成,每次枚舉一片新磚所能提供的條數及是否放角料,代價加1。每方向完整格數小於10,狀態很小;兩餘數之一為0時,不需要對應零寬邊條與角料。

a,b≤9,時間O((a+1)²(b+1)²),DP空間O((a+1)(b+1))。

Step-by-step animation

邊條與角料的裝箱計數DP|N=M=10,L=3,內部3×3需9片,另有6條寬1邊條與1×1角料。

回報動畫錯誤
步驟 1 / 3

分解

N=M=10,L=3,內部3×3需9片,另有6條寬1邊條與1×1角料。

內部9
邊條6
角料1
內部
9

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
int main() {
    int N, M, L;
    cin >> N >> M >> L;
    int a = N / L, b = M / L, r = N % L, s = M % L, base = a * b;
    int A = s ? a : 0, B = r ? b : 0, corner = r && s;
    vector<vector<array<int, 2>>> d(
        A + 1, vector<array<int, 2>>(B + 1, array<int, 2>{1000, 1000}));
    d[0][0][!corner] = 0;
    for (int x = 0; x <= A; x++)
        for (int y = 0; y <= B; y++)
            for (int z = 0; z < 2; z++)
                if (d[x][y][z] < 1000)
                    for (int i = 0; x + i <= A; i++)
                        for (int j = 0; y + j <= B; j++) {
                            int remain = L - i * s - j * r;
                            if (remain < 0)
                                continue;
                            for (int take = 0; take <= 1 - z; take++) {
                                if (!i && !j && !take)
                                    continue;
                                if (take && remain < min(r, s))
                                    continue;
                                int &v = d[x + i][y + j][z | take];
                                v = min(v, d[x][y][z] + 1);
                            }
                        }
    cout << base + d[A][B][1] << "\n";
}

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

更多