分别计算上下和左右移动的最小距离,取min即可
void solve(int u){ cin>>n>>m; int a,b,c,d,e,f; cin>>a>>b>>c>>d>>e>>f; ll x=min(abs(a-c),n-abs(a-c)),y=min(abs(b-d),m-abs(b-d)); ll x1=min(abs(c-e),n-abs(c-e)),y1=min(abs(d-f),m-abs(d-f)); cout<<x1+x+y+y1<<endl; }
对于非叶子节点贡献+1
对于叶子节点,设叶子节点深度为d 贡献+(k-d+1)
#include <bits/stdc++.h> using namespace std; typedef pair<int, int>PII; #define x first #define y second typedef long long ll; const int N = 2E5 + 10, mod = 1e9 + 7; int T, w[N], n,k; vector<int>g[N]; int d[N]; ll res; void dfs(int u,int fa,int d){ if(g[u].size()==1&&g[u][0]==fa){ if(d<=k){ res+=k-d+1; } return; } if(d<=k)res++; for(int &x:g[u]){ if(x==fa)continue; dfs(x,u,d+1); } } void solve(int u) { cin>>n>>k; for(int i=1;i<n;i++){ int a,b; cin>>a>>b; g[a].push_back(b); g[b].push_back(a); } dfs(1,-1,0); cout<<res<<endl; } int main() { T = 1; for (int i = 1; i <= T; i++) { solve(i); } return 0; }
期望DP 笔试的时候没推出来,纯菜呜呜
#米哈游笔试##秋招##后端开发##互联网大厂#