- 非负边权的方法(两次 )
- 随便选择一个点当做起点 ,从起点出发寻找最长的路径( 到 )
- 继续用t当做起点,从 出发寻找最长路径,此时求出的最长路径就是直径
Ac Code
#include<bits/stdc++.h>
using namespace std;
const int N=1e5+7;
vector<int> s[N];
int n;
int maxn=0,pos=0;
void dfs(int u,int fa,int sum){
if(sum>maxn){
maxn=sum;
pos=u;
}
for(int i=0;i<s[u].size();i++){
int v=s[u][i];
if(v!=fa){
dfs(v,u,sum+1);
}
}
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin>>n;
for(int i=1;i<n;i++){
int u,v;
cin>>u>>v;
s[u].push_back(v);
s[v].push_back(u);
}
dfs(1,0,0);
int s=pos;
dfs(s,0,0);
cout<<maxn;
return 0;
} - 树形 写法
找到所有 作为中间点的最长路径或者是找到所有 作为端点的最长路径
上述的所有答案都可以表示为 作为起点的最长链 次长链
①确定状态
:表示以 为根的子树内的最长链
②确定答案
③确定状态转移方程
(选和不选)
④确定初始值和边界条件
Ac Code
#include<bits/stdc++.h>
using namespace std;
const int N=1e5+7;
vector<int> s[N];
int n;
int maxn=0;
//一个存最长链,一个存次长链
int dp1[N],dp2[N];
void dfs(int u,int fa){
for(int i=0;i<s[u].size();i++){
int v=s[u][i];
if(v!=fa){
dfs(v,u);
}
}
for(int i=0;i<s[u].size();i++){
int v=s[u][i];
if(v!=fa){
//操作和考试第三题一样
int tmp=max(0,dp1[v]+1);
if(tmp>dp1[u]){
dp2[u]=dp1[u];
dp1[u]=tmp;
}
else if(tmp>dp2[u]){
dp2[u]=tmp;
}
}
}
//取最大值
maxn=max(maxn,dp1[u]+dp2[u]);
return;
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin>>n;
for(int i=1;i<n;i++){
int u,v;
cin>>u>>v;
s[u].push_back(v);
s[v].push_back(u);
}
dfs(1,0);
cout<<maxn;
return 0;
} 求直径的同时,套个并查集求连通块
连通块一定是并查集内部的树形结果
和 的直径合并,答案可能来自:
- 的直径
- 的直径
- 的直径的一半 的直径的一半
Ac Code
#include<bits/stdc++.h>
using namespace std;
const int N=3e5+7;
vector<int> s[N];
int n,m,q;
int fa[N],c[N];
int dp1[N],dp2[N];
int maxn=0;
//并查集模版
int find(int x){
if(fa[x]==x){
return x;
}
return fa[x]=find(fa[x]);
}
void sunion(int x,int y){
x=find(x),y=find(y);
if(x!=y){
fa[y]=x;//不能写反
}
return;
}
//求树的直径
void dfs(int u,int fa){
for(int i=0;i<s[u].size();i++){
int v=s[u][i];
if(v!=fa){
dfs(v,u);
}
}
for(int i=0;i<s[u].size();i++){
int v=s[u][i];
if(v!=fa){
int tmp=max(0,1+dp1[v]);
if(tmp>dp1[u]){
dp2[u]=dp1[u];
dp1[u]=tmp;
}
else if(tmp>dp2[u]){
dp2[u]=tmp;
}
}
}
maxn=max(maxn,dp1[u]+dp2[u]);
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin>>n>>m>>q;
//并查集初始化
for(int i=1;i<=n;i++){
fa[i]=i;
}
while(m--){
int u,v;
cin>>u>>v;
s[u].push_back(v);
s[v].push_back(u);
sunion(u,v);
}
for(int i=1;i<=n;i++){
//每个祖先节点只用跑一次
if(find(i)!=i){
continue;
}
maxn=0;//归零
//不用初始化dp1,dp2
dfs(i,0);
c[i]=maxn;
}
while(q--){
int op;
cin>>op;
if(op==1){
int x;
cin>>x;
x=find(x);
cout<<c[x]<<'\n';
}
else{
int x,y;
cin>>x>>y;
x=find(x),y=find(y);
if(x==y){
continue;
}
//求新的直径
c[x]=c[y]=max(int(ceil(c[x]/2.0))+int(ceil(c[y]/2.0))+1,max(c[x],c[y]));
//记得连接连通块
sunion(x,y);
}
}
return 0;
}