2039. 网络空闲的时刻
BFS
先构建邻接表 然后统计0号节点到每个和节点的最短距离
然后维护每个节点发送信息的最大时间,这时可分为两种情况 对于节点 v v v
当 2 × dist ≤ patience [ v ] 2 \times \textit{dist} \le \textit{patience}[v] 2×dist≤patience[v]时,则此时节点 v v v还未开始发送第二次消息就已收到回复,因此节点 v v v 只会发送一次消息,则此时节点 v v v 变为空闲的时间为 2 × dist + 1 2 \times \textit{dist} + 1 2×dist+1。
当 2 × dist > patience [ v ] 2 \times \textit{dist} > \textit{patience}[v] 2×dist>patience[v] 时,则此时节点还在等待第一次发送消息的回复时,就会开始再次重发消息,所以计算在收到回复之后还继续发送了多少次消息,共发送 ⌊ 2 × dist − 1 patience [ i ] ⌋ \Big\lfloor\dfrac{2 \times \textit{dist}-1}{\textit{patience}[i]}\Big\rfloor ⌊patience[i]2×dist−1⌋次消息。因此节点 v v v 最后一次收到回复的时间为 patience [ v ] × ⌊ 2 × dist − 1 patience [ v ] ⌋ + 2 × dist \textit{patience}[v] \times \Big\lfloor\dfrac{2 \times \textit{dist}-1}{\textit{patience}[v]}\Big\rfloor + 2 \times \textit{dist} patience[v]×⌊patience[v]2×dist−1⌋+2×dist则此时可知节点 vv 变为空闲的时间为 patience [ v ] × ⌊ 2 × dist − 1 patience [ v ] ⌋ + 2 × dist + 1 \textit{patience}[v] \times \Big\lfloor\dfrac{2 \times \textit{dist}-1}{\textit{patience}[v]}\Big\rfloor + 2 \times \textit{dist} + 1 patience[v]×⌊patience[v]2×dist−1⌋+2×dist+1
class Solution {
public:
int networkBecomesIdle(vector<vector<int>>& edges, vector<int>& patience) {
int n = patience.size();
int res =0;
vector<vector<int>> graph(n,vector<int>());
vector<int> dis(n,-1);
dis[0] =0;
for (auto &edge:edges){
graph[edge[0]].push_back(edge[1]);
graph[edge[1]].push_back(edge[0]);
}
queue<pair<int,int>> q ;
q.push({0,0});
while(!q.empty()){
auto one =q.front();
int node=one.first,d=one.second;
q.pop();
for (auto & ner :graph[node]){
if (dis[ner]==-1){
dis[ner]=d+1;
q.push({ner,d+1});
int time = patience[ner] * ((2 * dis[ner] - 1) / patience[ner]) + 2 * dis[ner] + 1;
res = max(res, time);
}
}
}
return res;
}
};
221. 最大正方形
DP
d p [ i ] [ j ] = m i n ( d p [ i − 1 ] [ j − 1 ] , d p [ i − 1 ] [ j ] , d p [ i ] [ j − 1 ] ) + 1 dp[i][j] =min(dp[i-1][j-1],dp[i-1][j],dp[i][j-1])+1 dp[i][j]=min(dp[i−1][j−1],dp[i−1][j],dp[i][j−1])+1
class Solution {
public:
int maximalSquare(vector<vector<char>>& matrix) {
int m =matrix.size(),n=matrix[0].size();
vector<vector<int>> dp(m+1,vector<int>(n+1,0));
int res =0;
for (int i =1;i<=m;i++){
for(int j =1;j<=n;j++){
if (matrix[i-1][j-1]=='1'){
dp[i][j] =min(dp[i-1][j-1],min(dp[i-1][j],dp[i][j-1]))+1;
res =max(res,dp[i][j]);
}
}
}
return res*res;
}
};