結果

問題 No.386 貪欲な領主
ユーザー kotatsugamekotatsugame
提出日時 2020-02-23 17:18:29
言語 C++14
(gcc 13.2.0 + boost 1.83.0)
結果
AC  
実行時間 307 ms / 2,000 ms
コード長 991 bytes
コンパイル時間 565 ms
コンパイル使用メモリ 71,588 KB
実行使用メモリ 25,088 KB
最終ジャッジ日時 2024-04-18 11:34:43
合計ジャッジ時間 3,490 ms
ジャッジサーバーID
(参考情報)
judge4 / judge2
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 4 ms
6,656 KB
testcase_01 AC 5 ms
6,784 KB
testcase_02 AC 4 ms
6,912 KB
testcase_03 AC 4 ms
6,784 KB
testcase_04 AC 307 ms
25,088 KB
testcase_05 AC 244 ms
19,072 KB
testcase_06 AC 231 ms
18,944 KB
testcase_07 AC 6 ms
6,912 KB
testcase_08 AC 35 ms
7,936 KB
testcase_09 AC 9 ms
6,784 KB
testcase_10 AC 5 ms
6,784 KB
testcase_11 AC 4 ms
6,912 KB
testcase_12 AC 6 ms
6,656 KB
testcase_13 AC 10 ms
7,168 KB
testcase_14 AC 234 ms
18,944 KB
testcase_15 AC 249 ms
25,088 KB
権限があれば一括ダウンロードができます
コンパイルメッセージ
main.cpp:41:1: warning: ISO C++ forbids declaration of 'main' with no type [-Wreturn-type]
   41 | main()
      | ^~~~

ソースコード

diff #

#include<iostream>
#include<vector>
using namespace std;
int N;
vector<int>G[1<<17];
int pa[20][1<<17];
int cumsum[1<<17];
int depth[1<<17];
int U[1<<17];
void dfs(int u,int p,int cu,int d)
{
	cumsum[u]=cu+=U[u];
	pa[0][u]=p;
	depth[u]=d++;
	for(int v:G[u])
	{
		if(v!=p)
		{
			dfs(v,u,cu,d);
		}
	}
}
int lca(int u,int v)
{
	if(depth[u]<depth[v])u^=v^=u^=v;
	for(int k=0;k<20;k++)
	{
		if(depth[u]-depth[v]>>k&1)u=pa[k][u];
	}
	if(u==v)return u;
	for(int k=20;k--;)
	{
		if(pa[k][u]!=pa[k][v])
		{
			u=pa[k][u];
			v=pa[k][v];
		}
	}
	return pa[0][u];
}
main()
{
	cin>>N;
	for(int i=1;i<N;i++)
	{
		int u,v;cin>>u>>v;
		G[u].push_back(v);
		G[v].push_back(u);
	}
	for(int i=0;i<N;i++)cin>>U[i];
	dfs(0,-1,0,0);
	for(int k=1;k<20;k++)for(int i=0;i<N;i++)
	{
		if(pa[k-1][i]>=0)pa[k][i]=pa[k-1][pa[k-1][i]];
		else pa[k][i]=-1;
	}
	int M;cin>>M;
	long ans=0;
	for(;M--;)
	{
		int u,v,c;cin>>u>>v>>c;
		int g=lca(u,v);
		ans+=c*(cumsum[u]+cumsum[v]-2*cumsum[g]+U[g]);
	}
	cout<<ans<<endl;
}
0