atcoder beginner contest(abc 394)F题题解

题目链接F - Alkane

题意

给出一个由n个节点组成的树状无向图,让我们搜索其子图中,包含节点数最多且每个节点度数都为1或4,同时保证至少有一个节点度数为4的子图

思路

题目简单明了可以看出要用到dfs或者dp,当然按照官方题解上的dp也为一种很好的解决方法,但是我觉得dfs实现起来更容易接受,最主要比较格式化,而dp相对灵活,不易形成一种公式化的套路。

首先我们要思考如何存储这个无向图,显然我们需要一个邻接表,我们想到用板子就行,但是这个邻接表不需要开next数组去连接,因为我们不需要去做增删查这些操作,是一个树状图,实现搜索只需要存每个节点的子节点是谁即可。其次我们需要思考如何实现要求子图中节点的度数为1或者4的要求,那么对于我们搜索到的这个节点如果子节点数多余三个,那么只要只要选取节点数最多的三个子节点形成的三个子树,一定最优,若小于3,则只选取一个节点数最多的子节点形成的树,以此类推,每次取用贪心策略更新以每个节点为根节点的符合要求的树中总的节点数,如果最后答案小于5则无解,因为这个图中要求至少有一个点的度数为4,否则输出答案。

代码

#include<iostream>
#include<algorithm>
#include<cstring>
//#include<cmath>
#include<vector>
//#include<queue>
//#include<set>
//#include<map>
//#include<stack>
//#include<unordered_map>
//#define int long long
#define IOS ios::sync_with_stdio(0); cin.tie(0),cout.tie(0);
#define debug(x) cout << #x << " = " << x << '\n';
#define endl '\n'
#define F first
#define S second
#define LL long long
#define PII pair<int, int>
using namespace std;
const double eps = 1e-8;
const int N = 2e5 + 10;

int ans = 0, f[N];
vector<int> vt[N];

void dfs(int x, int lst)
{
	f[x] = 1;
	vector<int> s;
	for(auto y : vt[x])
		if(y != lst)
		{
			dfs(y, x);
		    s.push_back(f[y]);
		}
	
	sort(s.begin(), s.end(), greater<int>());
	if(!s.empty()) ans = max(ans, s[0] + 1);
	if(s.size() >= 4) ans = max(ans, s[0] + s[1] + s[2] + s[3] + 1);
	if(s.size() >= 3) f[x] = max(f[x], s[0] + s[1] + s[2] + 1);
	return;
}

signed main()
{
	int n;
	cin >> n;
	int x, y;
	for(int i = 0; i < n - 1; ++ i)
	{
		cin >> x >> y;
		x --, y --;
		vt[x].push_back(y);
		vt[y].push_back(x);
	}
	dfs(0, -1);
	if(ans <= 4) cout << -1 << endl;
	else cout << ans << endl;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值