b658困難
雙片套印的單孔輪廓
枚舉所有可能相交位移,判斷單洞與四連通並統計最小周長的位移數。
效能範圍:來源未提供評測時限。WSL 本機35×35兩張全黑圖實測:Python約15.90秒、C++17約0.34秒;此案例已觸及全部平移。Python大界執行成本高,嚴格時限建議使用C++17,不能保證Python通過未知時限。
解題思路
非空交集要求 dx 在 [1−hB,hA−1]、dy 在 [1−wB,wA−1];只需枚舉這些位移。以黑格集合建立交集與聯集,先檢查兩者是否各自四連通。周長可由每個黑格四鄰中不存在的格數相加。
在涵蓋兩圖的矩形外再加一圈白格。白格洪水填充的連通塊中,恰一塊接觸外框,代表無限背景,其餘每塊各是一個洞。因此白塊總數恰為二才合格。枚舉每個位移一次,再對最小周長累加位移數,就算聯集相同也不會漏算不同位移。
設 T=(hA+hB−1)(wA+wB−1),G=(hA+hB+2)(wA+wB+2)。時間 O(TG)、額外 O(G);尺寸至多35時 T≤4761、G≤5184。Python 圖樣與輸入緩衝 O(G),沒有枚舉無界平面。
Step-by-step animation
逐步教學推演:依各步描述的例子觀察狀態、轉移與答案。
步驟 1 / 3
外框圖樣
A 是 3×3 黑環,B 單黑格放在左上角。
111
101
111
- 交集格數
- 1
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const ll MOD = 1000000007;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int ha, wa, hb, wb;
cin >> ha >> wa >> hb >> wb;
vector<pair<int, int>> A, B;
string s;
for (int r = 0; r < ha; r++) {
cin >> s;
for (int c = 0; c < wa; c++)
if (s[c] == '1')
A.push_back({r, c});
}
for (int r = 0; r < hb; r++) {
cin >> s;
for (int c = 0; c < wb; c++)
if (s[c] == '1')
B.push_back({r, c});
}
if (A.empty() || B.empty()) {
cout << "-1 0\n";
return 0;
}
int best = INT_MAX, ways = 0;
int dr[] = {1, -1, 0, 0}, dc[] = {0, 0, 1, -1};
for (int dx = 1 - hb; dx < ha; dx++)
for (int dy = 1 - wb; dy < wa; dy++) {
int x0 = min(0, dx) - 1, y0 = min(0, dy) - 1, H = max(ha, dx + hb) - x0 + 1,
W = max(wa, dy + wb) - y0 + 1;
vector<int> a(H * W), b(H * W);
for (auto [r, c] : A)
a[(r - x0) * W + c - y0] = 1;
for (auto [r, c] : B)
b[(r + dx - x0) * W + c + dy - y0] = 1;
auto comp = [&](int kind) {
vector<char> vis(H * W);
int ans = 0;
for (int i = 0; i < H * W; i++) {
bool ok = kind == 0 ? (a[i] && b[i])
: kind == 1 ? (a[i] || b[i])
: !(a[i] || b[i]);
if (!ok || vis[i])
continue;
ans++;
vector<int> st{i};
vis[i] = 1;
while (!st.empty()) {
int z = st.back();
st.pop_back();
int r = z / W, c = z % W;
for (int d = 0; d < 4; d++) {
int nr = r + dr[d], nc = c + dc[d];
if (nr < 0 || nr >= H || nc < 0 || nc >= W)
continue;
int j = nr * W + nc;
bool good = kind == 0 ? (a[j] && b[j])
: kind == 1 ? (a[j] || b[j])
: !(a[j] || b[j]);
if (good && !vis[j]) {
vis[j] = 1;
st.push_back(j);
}
}
}
}
return ans;
};
if (comp(0) != 1 || comp(1) != 1 || comp(2) != 2)
continue;
int per = 0;
for (int r = 1; r < H - 1; r++)
for (int c = 1; c < W - 1; c++)
if (a[r * W + c] || b[r * W + c])
for (int d = 0; d < 4; d++) {
int j = (r + dr[d]) * W + c + dc[d];
per += !(a[j] || b[j]);
}
if (per < best) {
best = per;
ways = 1;
} else if (per == best)
ways++;
}
cout << (ways ? best : -1) << ' ' << ways << '\n';
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。