lc2975
计算水平/垂直栅栏(补全外围后)的所有间距
auto f = [&](vector<int>& a,int mv) -> unordered_set<int>
for (int d : vs)
if (hs.count(d) && d > max_l) {
集合存储水平间距,遍历垂直间距找到++两者共有的最大间距作为正方形边长++
class Solution {
public:
int maximizeSquareArea(int m, int n, vector<int>& h, vector<int>& v) {
const int mod = 1e9 + 7;
++auto f = [&](vector<int>& a,int mv) -> unordered_set<int> {++
a.push_back(1);
a.push_back(mv);
sort(a.begin(), a.end());
unordered_set<int> s;
for (int i = 0; i < a.size(); ++i) {
for (int j = i + 1; j < a.size(); ++j) {
s.insert(a[j] - a[i]);
}
}
return s;
};
auto hs = f(h,m);
auto vs = f(v,n);
int max_l = -1;
++for (int d : vs) {++
++if (hs.count(d) && d > max_l) {++
max_l = d;
}
}
if (max_l == -1) return -1;
long long res = (long long)max_l * max_l % mod;
return (int)res;
}
};
lc1301
先将起点终点置0初始化DP和路径数数组,从左上到右下遍历网格
跳过障碍后取上、左、左上方向的最大得分并累加对应路径数
最终返回右下角的最大得分和路径数(无路径则返回[0,0])
class Solution {
public:
vector<int> pathsWithMaxScore(vector<string>& board) {
int mod = 1e9+7;
int n = board.size(), m = board[0].size();
vector f(n+10,vector<long long>(m+10,LONG_MIN/2)), g(n+10,vector<long long>(m+10,0));
board[0][0] = board[n-1][m-1] = '0';
// 这个初始化!! 一定要左上角位置初始化 不然是会影响 (1,1) 相邻点结果,导致最终结果不对
f[0][0] = 0;
g[0][0] = 1;
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
if(board[i-1][j-1] == 'X') continue;
int val = board[i-1][j-1]-'0';
// 先更新最大值 再判断
long long mx_f = max({f[i-1][j], f[i][j-1], f[i-1][j-1]});
if(mx_f == LONG_MIN/2) continue; // 不可达判断方法!!
f[i][j] = mx_f + val; // 当前i,j 最大值;
long long cnt = 0;
if(f[i-1][j] == mx_f) cnt += g[i-1][j];
if(f[i][j-1] == mx_f) cnt += g[i][j-1];
if(f[i-1][j-1] == mx_f) cnt += g[i-1][j-1];
g[i][j] = cnt % mod; // 必要
}
}
if(f[n][m] == LONG_MIN/2){
return {0,0};
}
return {(int)f[n][m], (int)g[n][m] % mod};
}
};
lc1001
hash计灯在行列、正负对角线的覆盖次数,查询时判断目标格是否被照亮,随后关闭查询格周围3×3区域的灯并更新统计

class Solution {
public:
unordered_map<int, int> ver, hor;
unordered_map<int, int> d1, d2;
set<pair<int,int>> st;
void add(pair<int,int> pr) {
if(st.count(pr))return;
ver[pr.first]++;
hor[pr.second]++;
d1[pr.first+pr.second]++;
d2[pr.first-pr.second]++;
st.insert(pr);
}
void close(pair<int,int> pr) {
ver[pr.first]--;
hor[pr.second]--;
d1[pr.first+pr.second]--;
d2[pr.first-pr.second]--;
st.erase(pr);
}
int query(pair<int,int> pr) {
return ver[pr.first] > 0 || hor[pr.second] > 0 || d1[pr.first+pr.second] > 0 || d2[pr.first-pr.second] > 0;
}
vector<int> gridIllumination(int N, vector<vector<int>>& lamps, vector<vector<int>>& queries) {
for(auto e: lamps)
++add(make_pair(e[0], e[1]));++
vector<int> ans;
for(auto e: queries)
{
int x = e[0], y = e[1];
++ans.push_back(query(make_pair(x,y)));++
for(int i = -1 ; i <= 1 ; i++) {
for(int j = -1 ; j <= 1 ; j++) {
++if(st.count(make_pair(x+i, y+j)))
close(make_pair(x+i,y+j));++
}
}
}
return ans;
}
};