题目大意:向一棵树加入k(k=1 or 2)条边之后,使得从1号点走过所有边再回到1号点的总路程最小,求最小路程。
显然,我们可以贪心去做。
当k=1时,很明显我们加的边的起点和终点的距离越大越好,即找到树的直径的长度max,ans=2*(n-1)-max+1。
当k=2时,上述方法看似行不通了,但是我们第二次连边所减少的距离Δdist=max-len*2+1,其中Max代表树的直径,len代表重复的路径长度。得到重复的路径长度不算太难,只要在第一次求直径时把起点和终点记录下来,然后把边权改为-1就好了。
代码如下:
#include <cstdio>
#include <cstring>
#define maxn 100005
using namespace std;
int n,op,st,ed,ans,max,maxx;
int pre[maxn*2],now[maxn],son[maxn*2],v[maxn*2],tot;
int p[maxn],d[maxn],dist[maxn],fa[maxn],fap[maxn],fir[maxn],sec[maxn];
void build(int a,int b){
pre[++tot]=now[a];
now[a]=tot;
son[tot]=b;
v[tot]=1;
}
void dfs2(int x,int ffa){
if (dist[x]>max)
{
max=dist[x];
maxx=x;
}
for (int p=now[x];p;p=pre[p])
if (son[p]!=ffa)
{
dist[son[p]]=dist[x]+v[p];
fa[son[p]]=x;
fap[son[p]]=p;
dfs2(son[p],x);
}
}
void bfs2(int a){
int top=1;d[1]=a; p[a]=now[a]; fa[a]=0;
while (top)
{
int x=d[top];
if (!p[x])
{
top--;
if (top)
p[fa[x]]=pre[p[fa[x]]];
continue;
}
int y=son[p[x]];
if (y!=fa[x])
{
dist[y]=dist[x]+v[p[x]];
fa[y]=x;
fap[y]=p[x];
d[++top]=y;
p[y]=now[y];
if (dist[y]>max)
{
max=dist[y];
maxx=y;
}
}
else
p[x]=pre[p[x]];
}
}
void dfs(int x,int ffa){
for (int p=now[x];p;p=pre[p])
if (son[p]!=ffa)
{
dfs(son[p],x);
if (fir[son[p]]+v[p]>fir[x])
{
sec[x]=fir[x];
fir[x]=fir[son[p]]+v[p];
}
else
if (fir[son[p]]+v[p]>sec[x])
sec[x]=fir[son[p]]+v[p];
}
if (fir[x]+sec[x]>max)
max=fir[x]+sec[x];
}
void bfs(){
d[1]=1; int top=1; p[1]=now[1]; fa[1]=0;
while (top){
int x=d[top];
if (!p[x])
{
top--;
if (fir[x]+sec[x]>max)
max=fir[x]+sec[x];
if (top)
{
if (fir[x]+v[fap[x]]>fir[fa[x]])
{
sec[fa[x]]=fir[fa[x]];
fir[fa[x]]=fir[x]+v[fap[x]];
}
else
if (fir[x]+v[fap[x]]>sec[fa[x]])
sec[fa[x]]=fir[x]+v[fap[x]];
p[fa[x]]=pre[p[fa[x]]];
}
continue;
}
int y=son[p[x]];
if (y!=fa[x])
{
fa[y]=x;
fap[y]=p[x];
d[++top]=y;
p[y]=now[y];
}
else
p[x]=pre[p[x]];
}
}
void doit(int st,int ed){
while (ed!=st)
{
v[fap[ed]]=-1;
if (fap[ed]%2==1)
v[fap[ed]+1]=-1;
else
v[fap[ed]-1]=-1;
ed=fa[ed];
}
}
int main(){
scanf("%d%d",&n,&op);
ans=2*(n-1);
for (int i=1;i<n;i++)
{
int a,b;
scanf("%d%d",&a,&b);
build(a,b);
build(b,a);
}
dist[1]=0;
bfs2(1);// 非递归找离1号点最远的点
//dfs2(1,0); //递归找离1号点最远的点
st=maxx;
dist[st]=0;
//dfs2(st,0);
bfs2(st);
ed=maxx;
ans=ans-max+1;
if (op==1)
{
printf("%d\n",ans);
return 0;
}
max=0;
doit(st,ed);//修改边权
//dfs(1,0);//递归找直径
bfs();//非递归找直径
ans=ans-max+1;
printf("%d\n",ans);
return 0;
}