Open Draymonders opened 4 years ago
本题是vip题,无奈,只能自己手搓了
就是求多叉树的直径
#include<bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<vector<int>> g;
int res = 0;
// 返回以u为跟的最长的一条路
int dfs(int u, int fa) {
int mx1=0, mx2=0;
for (int i=0; i<g[u].size(); i++) {
int v = g[u][i];
if (v == fa) continue;
int l = dfs(v, u);
if (l > mx1) {
mx2 = mx1;
mx1 = l;
} else if (l > mx2) {
mx2 = l;
}
}
res = max(res, mx1+mx2+1);
return mx1+1;
}
int treeDiameter(vector<vector<int>>& edges) {
int len = edges.size();
g.resize(len+5);
for (int i=0; i<=len; i++) g[i].clear();
res = 0;
for (auto edge : edges) {
int x = edge[0], y = edge[1];
g[x].push_back(y);
g[y].push_back(x);
}
dfs(0, -1);
return res - 1;
}
};
int main()
{
freopen("1245.txt", "r", stdin);
int n, m;
// m条边
vector<vector<int>> edges;
Solution s;
while (cin >> m) {
vector<vector<int>> edges;
for (int i=0; i<m; i++) {
int x, y;
cin >> x >> y;
edges.push_back({x, y});
}
int res = s.treeDiameter(edges);
cout << res << endl;
}
}
训练dp的一个不错的方式
线性DP
区间DP
记忆化递归
背包DP
树形DP
状态压缩DP
leetcode 526,464,935,1349
数位DP
leetcode902,1015,233
计数型DP
递推型DP
leetcode 50, 70,372,509,935,957, 1137
概率型DP
leetcode 808, 837
博弈型DP
策梅洛定理,SG定理 翻转游戏(leetcode293,294) Nim游戏(leetcode292) 石子游戏(leetcode877,1040) 井字游戏(leetcode348,794,1275)