QOJ.ac

QOJ

IDSubmission IDProblemHackerOwnerResultSubmit timeJudge time
#1167#735417#6814. Group HomeworkQFshengxiuQFshengxiuSuccess!2024-11-11 19:54:572024-11-11 19:54:57

Details

Extra Test:

Time Limit Exceeded

input:

200000
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1...

output:


result:


IDProblemSubmitterResultTimeMemoryLanguageFile sizeSubmit timeJudge time
#735417#6814. Group HomeworkQFshengxiuTL 673ms124388kbC++231.4kb2024-11-11 19:50:482024-11-11 19:56:22

answer

#include <bits/stdc++.h>
#define int long long
#define endl '\n'
using namespace std;
using PII = pair<int, int>;
const int N = 2e5 + 10;
int a[N];
int n, cnt, cnt2;
vector<int> g[N];
map<int, int> f[N], d[N];

int dfs(int u, int fa)
{

	if (d[u][fa])
		return d[u][fa];
	int maxn = a[u];
	for (auto v : g[u])
	{
		if (v == fa)
			continue;
		maxn = max(maxn, dfs(v, u) + a[u]);
	}

	return d[u][fa] = maxn;
}
int dfs2(int u, int fa)
{

	if (f[u][fa])
		return f[u][fa];
	vector<int> nx = {0, 0};
	int maxn = 0;
	for (auto v : g[u])
	{
		if (v == fa)
			continue;
		maxn = max(maxn, dfs2(v, u));
		nx.push_back(dfs(v, u));
	}
	sort(nx.begin(), nx.end(), [&](int a, int b)
		 { return a > b; });
	return f[u][fa] = max(maxn, nx[0] + nx[1] + a[u]);
}
void solve()
{
	cin >> n;
	for (int i = 1; i <= n; i++)
		cin >> a[i];
	for (int i = 1; i < n; i++)
	{
		int u, v;
		cin >> u >> v;
		g[u].push_back(v);
		g[v].push_back(u);
	}
	int ans = 0;
	for (int i = 1; i <= n; i++)
	{
		vector<int> dx = {0, 0, 0, 0};
		for (auto v : g[i])
			dx.push_back(dfs(v, i));
		sort(dx.begin(), dx.end(), [&](int a, int b)
			 { return a > b; });
		ans = max(ans, dx[0] + dx[1] + dx[2] + dx[3]);
	}
	for (int i = 1; i <= n; i++)
	{
		for (auto v : g[i])
		{
			ans = max(ans, dfs2(v, i) + dfs2(i, v));
		}
	}
	cout << ans << endl;
}
signed main()
{
	ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
	int T = 1;
	solve();
}