Stars Drawing (Hard Edition)

Stars Drawing (Hard Edition)

Created by LXC on Fri Sep 15 19:24:48 2023

https://codeforces.com/problemset/problem/1015/E2

ranting: 1900

tag: binary search, dp, greedy

problem

给出一个包含*.的n行m列的矩阵。
求其是否可以由至少1阶星星图组成,星星可以覆盖。

1到3阶的星星如下。
图片

solution

求出每个点作为星星的中心,最大阶数能有多大。

我们只需要知道每个点在四个方向上能延伸的长度,求出最小值便是最大阶数。这可以用记忆化搜索。

然后我们需要区间修改,对每一行每一列都用一个差分数组维护。这样做到区间修改$O(1)$

最后求一次前缀和,得到每一个点被覆盖次数。只要形状与原图一致,则有答案。

code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108

#include <bits/stdc++.h>
#define SINGLE_INPUT
#define ll long long
#define ull unsigned long long
#define N 1005
#define MOD 998244353
using namespace std;

int n, m;
string g[N];

int rd[N][N], cd[N][N];

int f[4][N][N];

int dfs(int d, int x, int y) {
if (x < 0 || x >= n || y < 0 || y >= m || g[x][y] == '.')
return 0;
if (f[d][x][y])
return f[d][x][y];
return f[d][x][y] = dfs(d, x + (d - 1) % 2, y + (d - 2) % 2) + 1;
}

void sol() {
cin >> n >> m;
for (int i = 0; i < n; i++) {
cin >> g[i];
}
vector<vector<int>> ans;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (g[i][j] == '*') {
int mn = N;
for (int k = 0; k < 4; k++) {
mn = min(mn, dfs(k, i, j));
}
// [i,j] [i-mn+1, i+mn-1] [j-mn+1, j+mn-1]
if (mn > 1) {
rd[i][j - mn + 1]++;
rd[i][j + mn]--;
cd[j][i - mn + 1]++;
cd[j][i + mn]--;
// cout << i << " " << j << " " << mn << "\n";
ans.push_back({i + 1, j + 1, mn - 1});
}
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 1; j < m; j++) {
rd[i][j] += rd[i][j - 1];
}
}
for (int i = 0; i < m; i++) {
for (int j = 1; j < n; j++) {
cd[i][j] += cd[i][j - 1];
}
}
// for (int i = 0; i < n; i++) {
// for (int j = 0; j < m; j++) {
// cout << rd[i][j] << " ";
// }
// cout << endl;
// }
// cout << endl;
// for (int i = 0; i < n; i++) {
// for (int j = 0; j < m; j++) {
// cout << cd[j][i] << " ";
// }
// cout << endl;
// }
// cout << endl;
int ok = 1;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (g[i][j] == '.' || rd[i][j] || cd[j][i])
continue;
ok = 0;
}
}
if (ok) {
cout << ans.size() << "\n";
for (auto& i : ans) {
cout << i[0] << " " << i[1] << " " << i[2] << "\n";
}
} else {
cout << "-1\n";
}
}

int main() {
cout << setprecision(15) << fixed;
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
#ifndef SINGLE_INPUT
int t;
cin >> t;
while (t--) {
sol();
}
#else
sol();
#endif
return 0;
}