結果

問題 No.386 貪欲な領主
ユーザー snrnsidysnrnsidy
提出日時 2021-08-27 06:01:53
言語 C++17
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 120 ms / 2,000 ms
コード長 2,040 bytes
コンパイル時間 2,220 ms
コンパイル使用メモリ 203,924 KB
実行使用メモリ 24,960 KB
最終ジャッジ日時 2024-04-29 22:09:32
合計ジャッジ時間 3,854 ms
ジャッジサーバーID
(参考情報)
judge1 / judge3
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 6 ms
13,312 KB
testcase_01 AC 5 ms
13,312 KB
testcase_02 AC 5 ms
13,184 KB
testcase_03 AC 5 ms
13,184 KB
testcase_04 AC 120 ms
24,960 KB
testcase_05 AC 110 ms
19,968 KB
testcase_06 AC 113 ms
19,712 KB
testcase_07 AC 6 ms
13,184 KB
testcase_08 AC 20 ms
13,952 KB
testcase_09 AC 8 ms
13,184 KB
testcase_10 AC 5 ms
13,184 KB
testcase_11 AC 6 ms
13,184 KB
testcase_12 AC 6 ms
13,056 KB
testcase_13 AC 8 ms
13,184 KB
testcase_14 AC 112 ms
19,712 KB
testcase_15 AC 102 ms
24,576 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>

using namespace std;

int n, m, a, b, c;
int parent[100000][18];
int depth[100000];
vector <int> adj[100000];
long long int u[100000];
int query[200000][3];
long long int arr[100000];

void dfs(int now)
{
	for (auto next : adj[now])
	{
		if (depth[next] == -1)
		{
			parent[next][0] = now;
			depth[next] = depth[now] + 1;
			dfs(next);
		}
	}
}

int getlca(int x, int y)
{
	if (depth[x] < depth[y])
	{
		int t = y;
		y = x;
		x = t;
	}

	int d = abs(depth[x] - depth[y]);

	for (int j = 0; d > 0; j++)
	{
		if (d % 2)
		{
			x = parent[x][j];
		}
		d /= 2;
	}

	if (x != y)
	{
		for (int j = 18 - 1; j >= 0; j--)
		{
			if (parent[x][j] != -1 && parent[x][j] != parent[y][j])
			{
				x = parent[x][j];
				y = parent[y][j];
			}
		}

		x = parent[x][0];
	}

	return x;
}

void func(int now,int prev,long long int sum)
{
	sum += u[now];
	arr[now] = sum;
	for (auto next : adj[now])
	{
		if (next == prev) continue;
		func(next, now, sum);
	}
}

int main(void)
{
	cin.tie(0);
	ios::sync_with_stdio(false);
	
	cin >> n;

	for (int i = 0; i < n - 1; i++)
	{
		cin >> a >> b;
		adj[a].push_back(b);
		adj[b].push_back(a);
	}

	for (int i = 0; i < n; i++)
	{
		cin >> u[i];
	}

	cin >> m;

	for (int i = 0; i < m; i++)
	{
		cin >> query[i][0] >> query[i][1] >> query[i][2];
	}


	memset(parent, -1, sizeof(parent));
	memset(depth, -1, sizeof(depth));
	depth[0] = 0;
	dfs(0);

	func(0, -1, 0);

	for (int i = 0; i < 17; i++)
	{
		for (int j = 1; j < n; j++)
		{
			if (parent[j][i] != -1)
			{
				parent[j][i + 1] = parent[parent[j][i]][i];
			}
		}
	}

	long long int res = 0;
	for (int i = 0; i < m; i++)
	{
		a = query[i][0];
		b = query[i][1];
		c = query[i][2];
		long long int lca = getlca(a, b);
		//cout << a << ' ' << b << ' ' << lca << '\n';
		if (lca > 0)
		{
			long long int sum = arr[a] - arr[parent[lca][0]];
			sum += (arr[b] - arr[lca]);
			res += (sum * c);
		}
		else
		{
			long long int sum = arr[a];
			sum += (arr[b] - arr[lca]);
			res += (sum * c);
		}
	}

	cout << res << '\n';

	return 0;
}
0