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.
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.
Print a single integer — the minimum number of seconds one needs to spend in order to visit all the cities exactly once.
5 2 3 1 2 1 3 3 4 5 3
9
5 3 2 1 2 1 3 3 4 5 3
8
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 .
题意:给你n个点,任意两点之间都有一条边,然后给你其中n-1条边的权值为x,剩下的所有边权值为y,
提可以随意规定路线、起点、终点,使得从一个点出发,经过所有点到某一点结束的路线最短。
题解:对于x>=y的情况是很好处理的,要么全走权值为y的边,要么其中一条边的权值为x,这种情况
也就是某一点是其他所有点的父亲的时候。。。
然而对于x<y的话就相对复杂点,我一开始想的求一发树的直径,秒wa3,前测还是很良心的,后来立马找到
自己的问题所在,因为我是直接走完直径后无脑全走权值为y的边的,这样肯定是错的,所以只有另想方法。
从我错的地方出发,不一定走完直径就不会再走权值为x的边了,因为可能还有短链存在。。。。
造几个样例就能发现只要某一点的儿子超过一个,呢就一定要走一条权值为y的边,越多走的y越多,因此我们
可以考虑常规搜索,然后对于每个点判断,边搜索边累计能够走权值为x的边的个数即可。。
再次附上惨图:
#include<vector>
#include<stdio.h>
#include<algorithm>
using namespace std;
typedef long long ll;
vector<ll>q[200005];
ll n,x,y,xx,yy,d;
int dfs(ll u,ll p)
{
int son=2;
for(ll i=0;i<q[u].size();i++)
{
ll v=q[u][i];
if(v==p)
continue;
if(dfs(v,u) && son>0)
d++,son--;
}
return son>0;
}
int main(void)
{
scanf("%lld%lld%lld",&n,&x,&y);
for(ll i=1;i<n;i++)
{
scanf("%lld%lld",&xx,&yy);
q[xx].push_back(yy);
q[yy].push_back(xx);
}
if(x>=y)
{
ll maxs=0,ans;
for(ll i=1;i<=n;i++)
maxs=max(maxs,(ll)q[i].size());
if(maxs==n-1)
ans=(n-2)*y+x;
else
ans=(n-1)*y;
printf("%lld\n",ans);
}
else
{
dfs(1,0);
printf("%lld\n",d*x+(n-1-d)*y);
}
return 0;
}