結果

問題 No.1103 Directed Length Sum
ユーザー snrnsidysnrnsidy
提出日時 2021-10-23 17:44:18
言語 C++17
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 852 ms / 3,000 ms
コード長 1,046 bytes
コンパイル時間 2,125 ms
コンパイル使用メモリ 203,656 KB
実行使用メモリ 136,444 KB
最終ジャッジ日時 2023-10-26 00:55:20
合計ジャッジ時間 13,000 ms
ジャッジサーバーID
(参考情報)
judge15 / judge12
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 15 ms
40,644 KB
testcase_01 AC 15 ms
40,644 KB
testcase_02 AC 344 ms
136,444 KB
testcase_03 AC 184 ms
46,332 KB
testcase_04 AC 453 ms
51,796 KB
testcase_05 AC 852 ms
58,468 KB
testcase_06 AC 273 ms
48,620 KB
testcase_07 AC 51 ms
42,072 KB
testcase_08 AC 77 ms
42,824 KB
testcase_09 AC 35 ms
41,548 KB
testcase_10 AC 122 ms
43,632 KB
testcase_11 AC 498 ms
52,632 KB
testcase_12 AC 275 ms
48,684 KB
testcase_13 AC 116 ms
43,716 KB
testcase_14 AC 30 ms
41,324 KB
testcase_15 AC 210 ms
45,316 KB
testcase_16 AC 585 ms
53,848 KB
testcase_17 AC 604 ms
54,344 KB
testcase_18 AC 117 ms
43,612 KB
testcase_19 AC 524 ms
52,876 KB
testcase_20 AC 42 ms
41,736 KB
testcase_21 AC 72 ms
42,620 KB
testcase_22 AC 416 ms
51,004 KB
testcase_23 AC 226 ms
45,624 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
 
using namespace std;
 
vector <int> adj[1000001];
int indegree[1000001];
int n,a,b;
int cnt[1000001];
long long int dp[1000001];
const long long int MOD = 1e9 + 7;

int dfs1(int now)
{
	if(cnt[now]!=-1)
	{
		return cnt[now];
	}
	cnt[now] = 1;
	for(auto next : adj[now])
	{
		cnt[now] += dfs1(next);
	}
	return cnt[now];
}

long long int dfs2(int now)
{
	if(dp[now]!=-1)
	{
		return dp[now];
	}

	dp[now] = 0;
	for(auto next : adj[now])
	{
		dp[now] += (dfs2(next) + cnt[next]);
	}
	return dp[now];
}

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);
		indegree[b]++;
	}

	int root = -1;
	for(int i=1;i<=n;i++)
	{
		if(indegree[i]==0)
		{
			root = i;
			break;
		}
	}


	memset(cnt,-1,sizeof(cnt));
	memset(dp,-1,sizeof(dp));
	dfs1(root);
	dfs2(root);

	long long int res = 0;

	for(int i=1;i<=n;i++)
	{
		//cout << i << ' ' << cnt[i] << ' ' << dp[i] << '\n';
		res += dp[i];
		res%=MOD;
	}

	cout << res << '\n';

	return 0;	
}
0