CodeForces - 618D Hamiltonian Spanning Tree(贪心+思维)

题目链接:点击这里

题目大意:
给定一张 n n n 个点的完全图,又给出一颗这 n n n 个点的生成树,树边权为 x x x ,原图边权为 y y y ,求这张图的哈密顿通路权值和最小值

题目分析:
仔细想想,边的选择只有两种选择,要么选树边要么选原完全图的边。
x ≤ y x\le y xy 时,树边优先级高于原图边,我们因为一个点的度最多为 2 2 2 ,所以可以用一次 d f s dfs dfs 来算出用了 c n t cnt cnt 条树边,最后 x ∗ c n t + y ∗ ( n − c n t − 1 ) x*cnt+y*(n-cnt-1) xcnt+y(ncnt1) 就是答案。
x > y x>y x>y 时,树边优先级低于原图边,尽量全用原图边即可,需要额外考虑一个细节就是:菊花图不可避免的要使用一条树边来连接菊花图的中心

具体细节见代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<set>
#include<map>
#include<queue>
#include<stack>
#define ll long long
#define inf 0x3f3f3f3f
#define Inf 0x3f3f3f3f3f3f3f3f
#define int ll
using namespace std;
int read()
{
	int res = 0,flag = 1;
	char ch = getchar();
	while(ch<'0' || ch>'9')
	{
		if(ch == '-') flag = -1;
		ch = getchar();
	}
	while(ch>='0' && ch<='9')
	{
		res = (res<<3)+(res<<1)+(ch^48);//res*10+ch-'0';
		ch = getchar();
	}
	return res*flag;
}
const int maxn = 1e6+5;
const int mod = 1e9+7;
const double pi = acos(-1);
const double eps = 1e-8;
int n,x,y,cnt;
vector<int>g[maxn];
int dfs(int u,int fa)
{
	int out = 2;
	for(auto to:g[u])
	{
		if(to == fa) continue;
		if(dfs(to,u) && out) cnt++,out--;
	}
	return out;
}
signed main()
{
	n = read(),x = read(),y = read();
	for(int i = 1;i < n;i++)
	{
		int u = read(),v = read();
		g[u].push_back(v);
		g[v].push_back(u);
	}
	if(x <= y) dfs(1,0);
	else for(int i = 1;i <= n;i++) 
		if(g[i].size() == n-1) 
		{
			cnt++; break;
		}
	cout<<x*cnt+y*(n-cnt-1)<<endl;
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值