2020 BIT冬训-图&&DFS&&BFS O - Hamiltonian Spanning Tree CodeForces - 618D (点的度数,树的最小路径覆盖cy)
Problem Description
A group of n cities is connected by a network of roads. There is an undirected road between every pair of cities, so there are roads in total. It takes exactly y seconds to traverse any single road.
A spanning tree is a set of roads containing exactly n - 1 roads such that it's possible to travel between any two cities using only these roads.
Some spanning tree of the initial network was chosen. For every road in this tree the time one needs to traverse this road was changed from y to x seconds. Note that it's not guaranteed that x is smaller than y.
You would like to travel through all the cities using the shortest path possible. Given n, x, y and a description of the spanning tree that was chosen, find the cost of the shortest path that starts in any city, ends in any city and visits all cities exactly once.
Input
The first line of the input contains three integers n, x and y (2 ≤ n ≤ 200 000, 1 ≤ x, y ≤ 109).
Each of the next n - 1 lines contains a description of a road in the spanning tree. The i-th of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n) — indices of the cities connected by the i-th road. It is guaranteed that these roads form a spanning tree.
Output
Print a single integer — the minimum number of seconds one needs to spend in order to visit all the cities exactly once.
Examples
5 2 3
1 2
1 3
3 4
5 3
9
5 3 2
1 2
1 3
3 4
5 3
8
Note
In the first sample, roads of the spanning tree have cost 2, while other roads have cost 3. One example of an optimal path is .
In the second sample, we have the same spanning tree, but roads in the spanning tree cost 3, while other roads cost 2. One example of an optimal path is .
当y<=x时。易得n-1边都是y或者当生成树为一个点连接剩下n-1个点时一条边为x,其余n-2个边为y。
当x<y时。应该加入最多的生成树上的边,再加入一些普通边来进行点的跳跃。
其中一种方法是求树的最小路径覆盖,用树上dp做即可。链接1,链接2,链接3。先mark一下
另一种是根据在链上每个点的度最多为2进行dfs来判断该点能否加入。
AC代码如下(第二种):
#include <algorithm> #include<iostream> #include<cstdio> #include<cstring> #include<vector> #include<queue> #define MAXN 200005 using namespace std; typedef long long ll; vector<int>g[MAXN]; int n,x,y,temp1,temp2,ans; int dfs(int x,int fa){ int d=2; for(int i=0;i<g[x].size();i++){ if(g[x][i]==fa) continue; int tmp=dfs(g[x][i],x); if(tmp&&d>0){ d--; ans++; } } return d>0?1:0; } int main(){ scanf("%d%d%d",&n,&x,&y); for(int i=0;i<n-1;i++){ scanf("%d%d",&temp1,&temp2); g[temp1].push_back(temp2); g[temp2].push_back(temp1); } if(x>=y){ int flag=0; for(int i=1;i<=n;i++){ if(g[i].size()==n-1){ flag=1; break; } } if(flag) printf("%lld\n",(n-2)*(ll)y+(ll)x); else printf("%lld\n",(n-1)*(ll)y); }else{ dfs(1,-1); printf("%lld\n",(ll)x*ans+(ll)y*(n-1-ans)); } }

浙公网安备 33010602011771号