样例过不了,求助
查看原帖
样例过不了,求助
494699
卷王慢即快楼主2023/1/23 15:06
#include <set>
#include <cstdio>
#include <iostream>
using namespace std;
const int maxn = 100007;
int n, m, tot = 0, cnt = 0;
int h[maxn];
struct node
{
	int to, nxt, value;
}e[maxn];
multiset<int> s[maxn];
inline void add(int u, int v, int w)
{
	e[++cnt].to = v;
	e[cnt].nxt = h[u];
	e[cnt].value = v;
	h[u] = cnt;
}
inline int read()
{
	int x = 0, f = 1;
	char ch = getchar();
	while(ch < '0' || ch > '9')
	{
		if(ch == '-') f = -1;
		ch = getchar();
	}
	while(ch >= '0' && ch <= '9')
	{
		x = (x << 1) + (x << 3) + (ch ^ 48);
		ch = getchar();
	}
	return x * f;
}
inline int dfs(int u, int f, int x)
{
	s[u].clear();
	for(int i = h[u]; i; i = e[i].nxt)
	{
		int v = e[i].to, w = e[i].value;
		if(v == f) continue;
		w += dfs(v, u, x);
		if(w >= x) tot++;
		else s[u].insert(w);
	}
	multiset<int> ::iterator it;
	int ans = 0;
	while(!s[u].empty())
	{
		if(s[u].size() == 1) return max(ans, *s[u].begin());
		it = s[u].lower_bound(x - *s[u].begin());
		if(it == s[u].begin() && s[u].count(*it) == 1) it++;
		if(it == s[u].end())
		{
			ans = max(ans, *s[u].begin());
			s[u].erase(s[u].find(*s[u].begin()));
		}
		else
		{
			tot++;
			s[u].erase(s[u].find(*it));
			s[u].erase(s[u].find(*s[u].begin()));
		}
	}
	return ans;
}
inline bool check(int x)
{
	tot = 0;
	dfs(1, 0, x);
	return cnt >= m;
}
int main()
{
	n = read(), m = read();
	for(int i = 1; i < n; i++)
	{
		int u = read(), v = read(), w = read();
		add(u, v, w); add(v, u, w);
	}
	int l = 1, r = 1e6, mid, ans = 0;
	while(l <= r)
	{
		mid = (l + r) >> 1;
		if(check(mid)) l = mid + 1, ans = mid;
		else r = mid - 1;
	}
	printf("%d", ans);
	return 0;
}
2023/1/23 15:06
加载中...