P4149求调
  • 板块灌水区
  • 楼主alpharchmage
  • 当前回复2
  • 已保存回复2
  • 发布时间2024/7/18 15:53
  • 上次更新2024/7/18 16:35:53
查看原帖
P4149求调
411141
alpharchmage楼主2024/7/18 15:53
#include<bits/stdc++.h>
#define int long long
using namespace std;
int n = 0 , m = 0 , cnt = 0 , tot = 0 , sum_now = 0 , root_now = 0 , res = INT_MAX;
array<int , 4000100> head , dp , sizes , vis , dep;
array<int , 4000100> dis;
array<pair<int , int> , 4000100> exist;
map<int , int> Map;
struct Node{
	int to;
	int nxt;
	int val;
};
array<Node , 4000100> edge;
void new_line(int a , int b , int c)
{
	edge.at(++ cnt).to = b;
	edge.at(cnt).nxt = head.at(a);
	edge.at(cnt).val = c;
	head.at(a) = cnt;
	return;
}
void get_root(int x , int fa)
{
	dp.at(x) = 0;
	sizes.at(x) = 1;
	for(int e = head.at(x);e;e = edge.at(e).nxt)
	{
		int to = edge.at(e).to;
		if(to != fa && !vis.at(to))
		{
			get_root(to , x);
			sizes.at(x) += sizes.at(to);
			dp.at(x) = max(dp.at(x), sizes.at(to));
		}
	}
	dp.at(x) = max(dp.at(x) , sum_now - sizes.at(x));
	if(dp.at(x) < dp.at(root_now)) 
	{
		root_now = x;
	}
}
void get_dis(int x, int fa)
{
	dep.at(x) = dep.at(fa) + 1;
	exist.at(++ tot) = {dis.at(x) , dep.at(x)};
	if(!Map[dis.at(x)])
	{
		Map[dis.at(x)] = dep.at(x);
	}
	else
	{
		Map[dis.at(x)] = min(Map[dis.at(x)] , dep.at(x));
	}
	for(int e = head.at(x);e;e = edge.at(e).nxt)
	{
		int to = edge.at(e).to;
		if(to != fa && !vis.at(to))
		{
			dis.at(to) = dis.at(x) + edge.at(e).val;
			get_dis(to , x);
		}
	}
}
void update(int x)
{
	int tmp = 0;
	dep.at(x) = 0;
	for(int e = head.at(x);e;e = edge.at(e).nxt)
	{
		int to = edge.at(e).to;
		if(!vis.at(to))
		{
			tot = 0;
			dis.at(to) = edge.at(e).val;
			get_dis(to , x);
			for(int i = 1;i <= tot;++ i)
			{
				if(m == exist.at(i).first)
				{
					res = min(res , exist.at(i).second);
				}
				else if(m > exist.at(i).first && Map[m - exist.at(i).first])
				{
					res = min(res , Map[m - exist.at(i).first] + exist.at(i).second);
				} 
			}
			for(int i = 1;i <= tot;++ i)
			{
				Map[exist.at(i).first] = min(Map[exist.at(i).first] , exist.at(i).second);
			}	
		}
	}
	Map.clear();
}
void dfs(int x)
{
	vis.at(x) = true;
	update(x);
	for(int e = head.at(x);e;e = edge.at(e).nxt)
	{
		int to = edge.at(e).to;
		if(!vis.at(to))
		{
			dp.at(n + 1) = n;
			sum_now = sizes.at(to);
			root_now = n + 1;
			get_root(to , x);
			dfs(root_now);
		}
	}
}
signed main()
{
	ios::sync_with_stdio(false);
	cin.tie(nullptr);
	cout.tie(nullptr);
	cin >> n >> m;
	for(int i = 1;i <= (n - 1);++ i)
	{
		int x = 0 , y = 0 , k = 0;
		cin >> x >> y >> k;
		new_line(x , y , k);
		new_line(y , x , k);
	}
	dp.at(n + 1) = n;
	sum_now = n;
	root_now = n + 1;
	get_root(0 , -1);
	dfs(root_now);
	if(res >= n)
	{
		cout << "-1" << endl;
		return 0;
	}
	cout << res << endl;
	return 0;
}
/*
10 10
1 2 10
1 3 1
3 4 1
4 5 1
5 6 1
6 7 1
7 8 1
8 9 1
9 10 3




*/
2024/7/18 15:53
加载中...