树环转换
Description
给定一棵N个节点的树,去掉这棵树的一条边需要消耗值1,为这个图的两个点加上一条边也需要消耗值1。树的节点编号从1开始。在这个问题中,你需要使用最小的消耗值(加边和删边操作)将这棵树转化为环,不允许有重边。
环的定义如下:
(1)该图有N个点,N条边。
(2)每个顶点的度数为2。
(3)任意两点是可达的。
树的定义如下:
(1)该图有N个点,N-1条边。
(2)任意两点是可达的。
Input
第一行是一个整数N代表节点的个数。
接下来N-1行每行有两个整数U, V(1 ≤ U, V ≤ N),表示双向边(U, V)
Output
输出把树转化为环的最小消耗值。
Sample Input
4
1 2
2 3
2 4
Sample Output
3
Solution
dfs。
Code
#include<iostream>
#include<vector>
#include<cstdio>
using namespace std;
#define N 1000001
vector<int>l[N];
int n,x,y,tot;
int dfs(int v,int fa){
int leaf=0;
for(int i=0;i<l[v].size();i++){
int u=l[v][i];
if(u==fa)continue;
leaf+=dfs(u,v);
}
if(leaf<2)return 1;
else{
if(v==1)tot+=leaf-2;
else tot+=leaf-1;
return 0;
}
}
int main(){
scanf("%d",&n);
for(int i=1;i<n;i++){
scanf("%d%d",&x,&y);
l[x].push_back(y);
l[y].push_back(x);
}
dfs(1,-1);
cout<<tot*2+1<<endl;
}