贪心做法求Hack
查看原帖
贪心做法求Hack
748239
OIbishop楼主2023/10/4 10:14
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int N = 5e5 + 5;
int n , t , val[N] , tim = 0 , cnt , dep[N] , pos , fa[N] , s[N] , cost[N] , ans , son , dfn[N] , low[N];
struct node {int to;};
vector <node> e[N];
void dfs (int u , int f)
{
	fa[u] = f; s[u] = 1 , dep[u] = dep[f] + 1;cost[u] = val[u];
	for (auto [v] : e[u])
	{
		if (v == f) continue;
		dfs (v , u);
		cost[u] += cost[v] , s[u] += s[v];
	}
}
bitset <N> vis;
void Find (int u)
{
	if (son == u) return;
	dfn[u] = tim;
//	cout << "\n";
//	cout << u << " " << tim << "\n";
	for (auto [v] : e[u])
	{
		if (v == fa[u] || v == son) continue;
		tim++;
		Find (v);
		tim++;
	}
}
set <int> line;
void Findson (int u)
{
	dfn[u] = tim;
//	cout << "\n"; 
//	cout << u << " " << tim << "\n";
	int now = 0;
	for (auto [v] : e[u])
	{
		if (v == fa[u]) continue;
		++tim;
		Findson (v);
		++tim;
	}
}
namespace MainFunction
{
	signed main ()
	{
		cin >> n >> t;
		for (int i = 2; i <= n; i++)
		{
			int u; cin >> u >> val[i];
			e[i].emplace_back ((node) {u});
			e[u].emplace_back ((node) {i});
		}
		dfs (1 , 1);
		for (int i = 1; i <= n; i++)
			sort (e[i].begin () , e[i].end () , [] (node x , node y) {return cost[x.to] > cost[y.to];});
		for (int i = 1; i <= n; i++)
			if (dep[pos] < dep[i] || (dep[pos] == dep[i] && cost[pos] > cost[i])) pos = i;
		if (t != 0)
		{
			son = pos;
			while (fa[son] != 1)
				son = fa[son];
		}
		else son = -1;
		int tmp = 2 * (n - 1);
		if (t == 0) cout << tmp << " ";
		else cout << tmp - dep[pos] + 1 << " ";
		Find (1); tim++;
		if (son != -1) Findson (son);
		for (int i = 1; i <= n; i++)
		{
				ans += dfn[i] * val[i];
//			cerr << "\n" << dfn[i] << " " << val[i] << "\n";
		}
		cout << ans << endl;
		return 0;
	}
}; signed main () {return MainFunction :: main ();};

RT

2023/10/4 10:14
加载中...