Submission #2522694


Source Code Expand

#define _USE_MATH_DEFINES

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <cmath>
#include <algorithm>
#include <vector>
#include <queue>
#include <map>

using namespace std;

#define MAX_V 110000
#define MAX_LOG_V 20

vector<int> G[MAX_V];

int parent[MAX_LOG_V][MAX_V]; // 2^k th parent
int depth[MAX_V]; // distance from root
int root = 0;

void dfs(int v, int p, int d){
	parent[0][v] = p;
	depth[v] = d;
	for(int i = 0; i < G[v].size(); i++){
		if(G[v][i] != p){
			dfs(G[v][i], v, d + 1);
		}
	}
}

void init(int V){
	for(int k = 0; k < MAX_LOG_V; k++){
		for(int v = 0; v < V; v++){
			parent[k][v] = -1;
			}else{
				parent[k + 1][v] = parent[k][parent[k][v]];
			}
		}
	}
	dfs(root, -1, 0);
	for(int k = 0; k < MAX_LOG_V - 1; k++){
		for(int v = 0; v < V; v++){
			if(parent[k][v] < 0){
				parent[k + 1][v] = -1;
			}else{
				parent[k + 1][v] = parent[k][parent[k][v]];
			}
		}
	}
}

int lca(int u, int v){
	if(depth[u] > depth[v]){
		swap(u, v);
	}
	for(int k = 0; k < MAX_LOG_V; k++){
		if((depth[v] - depth[u]) >> k & 1){
			v = parent[k][v];
		}
	}
	if(u == v){
		return u;
	}
	for(int k = MAX_LOG_V - 1; k >= 0; k--){
		if(parent[k][u] != parent[k][v]){
			u = parent[k][u];
			v = parent[k][v];
		}
	}
	return parent[0][u];
}

int main(){
	
	int N;
	cin >> N;
	
	for(int i = 0; i < N - 1; i++){
		int x, y;
		cin >> x >> y;
		x--;
		y--;
		if(x > y){
			swap(x, y);
		}
		G[x].push_back(y);
		G[y].push_back(x);
	}
	
	init(N);
	
	int Q;
	cin >> Q;
	
	for(int i = 0; i < Q; i++){
		int x, y;
		cin >> x >> y;
		x--;
		y--;
		int p = lca(x, y);
		cout << depth[y] - depth[p] - depth[p] + depth[x] + 1 << endl;
	}
	
	return 0;
}

Submission Info

Submission Time
Task D - 閉路
User monolith
Language C++14 (GCC 5.4.1)
Score 0
Code Size 1771 Byte
Status CE

Compile Error

./Main.cpp: In function ‘void init(int)’:
./Main.cpp:37:5: error: ‘else’ without a previous ‘if’
    }else{
     ^
./Main.cpp:38:19: error: ‘v’ was not declared in this scope
     parent[k + 1][v] = parent[k][parent[k][v]];
                   ^
./Main.cpp: At global scope:
./Main.cpp:42:5: error: expected constructor, destructor, or type conversion before ‘(’ token
  dfs(root, -1, 0);
     ^
./Main.cpp:43:2: error: expected unqualified-id before ‘for’
  for(int k = 0; k < MAX_LOG_V - 1; k++){
  ^
./Main.cpp:43:17: error: ‘k’ does not name a type
  for(int k = 0; k < MAX_LOG_V - 1; k++){
                 ^
./Main.cpp:43:36: error: ‘k’ does not name a type
  for(int k = 0; k < MAX_LOG_V - 1; k++){
                                    ^
./Main.cpp:52:1: error: expected declaration before ‘}’ token
 }
 ^