結果

問題 No.399 動的な領主
ユーザー chocoruskchocorusk
提出日時 2018-10-27 04:10:12
言語 C++11
(gcc 11.4.0)
結果
WA  
実行時間 -
コード長 1,603 bytes
コンパイル時間 950 ms
コンパイル使用メモリ 98,096 KB
実行使用メモリ 23,040 KB
最終ジャッジ日時 2024-04-29 22:10:18
合計ジャッジ時間 4,226 ms
ジャッジサーバーID
(参考情報)
judge1 / judge2
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 WA -
testcase_01 WA -
testcase_02 WA -
testcase_03 WA -
testcase_04 WA -
testcase_05 WA -
testcase_06 WA -
testcase_07 WA -
testcase_08 WA -
testcase_09 WA -
testcase_10 WA -
testcase_11 WA -
testcase_12 WA -
testcase_13 WA -
testcase_14 WA -
testcase_15 WA -
testcase_16 WA -
testcase_17 WA -
testcase_18 WA -
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <cstdio>
#include <cstring>
#include <iostream>
#include <string>
#include <cmath>
#include <bitset>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <algorithm>
#include <complex>
#include <unordered_map>
#include <unordered_set>
#include <random>
using namespace std;
typedef long long int ll;
typedef pair<int, int> P;
int n;
vector<int> g[100000];
int d[100000];
int p[17][100000];
bool used[100000];
void dfs0(int x){
	used[x]=1;
	for(auto y:g[x]){
		if(!used[y]){
			d[y]=d[x]+1;
			p[0][y]=x;
			dfs0(y);
		}
	}
}
ll ct[100000];
void dfs(int x){
	used[x]=1;
	for(auto y:g[x]){
		if(!used[y]){
			dfs(y);
			ct[x]+=ct[y];
		}
	}
}
int lca(int a, int b){
  if(d[a]>d[b]) swap(a, b);
    int a1=a, b1=b;
    int dd=d[b]-d[a], i=0;
    while(dd>0){
        if(dd%2==1){
            b1=p[i][b1];
        }
        dd/=2;
        i++;
    }
    if(a1==b1) return a1;
    for(int i=16; i>=0; i--){
        if(p[i][a1]!=p[i][b1]){
            a1=p[i][a1], b1=p[i][b1];
        }
    }
    return p[0][a1];
}

int main()
{
	cin>>n;
	for(int i=0; i<n-1; i++){
		int u, v;
		cin>>u>>v;
		u--; v--;
		g[u].push_back(v);
		g[v].push_back(u);
	}
	dfs0(0);
	for(int i=1; i<17; i++){
        for(int x=0; x<n; x++){
            p[i][x]=p[i-1][p[i-1][x]];
        }
    }
	int q;
	cin>>q;
	for(int t=0; t<q; t++){
		int a, b;
		cin>>a>>b;
		a--; b--;
		int c=lca(a, b);
		ct[a]++;
		ct[b]++;
		if(c>0){
			ct[p[0][c]]-=1;
		}
	}
	fill(used, used+n, 0);
	dfs(0);
	ll ans=0;
	for(int i=0; i<n; i++){
		ans+=(ct[i]*(ct[i]+1)/2);
	}
	cout<<ans<<endl;
    return 0;
}
0