HDU multi-school third 1002 Blow up the city - DAG inclusion and exclusion dominant tree +

Topic links: point I ah ╭ (╯ ^ ╰) ╮

Subject to the effect:

     n n cities composition directed acyclic graph, the degree of 0 0 city is headquarters city
     q q queries, each given two important cities
    ask any blow up a city, making it impossible to reach any two cities in a number of programs from the command of the city

Problem-solving ideas:

    First reverse map building to blow up the city is from the starting point to go through a number of points between the two cities
    is built directly D A G DAY dominant tree
    several starting point to go through the point of a city is the depth of this point
    the answer to both cities consider the inclusion and exclusion
    that is, minus the depth of two cities L C A LCA a depth, note that the source point

Core: DAG dominant tree features

#include<bits/stdc++.h>
#define rint register int
#define deb(x) cerr<<#x<<" = "<<(x)<<'\n';
using namespace std;
typedef long long ll;
typedef pair <int,int> pii;
const ll mod = 1e9 + 7;
const int maxn = 1e5 + 10;
int T, n, m, q, cnt;
int tp[maxn], in[maxn];
int dep[maxn], f[maxn][25];
vector <int> t[maxn];
vector <int> v[maxn], fa[maxn];

int lca(int x, int y){
	if(dep[x]<dep[y]) swap(x, y);
	for(int i=20; ~i; i--)
		if(dep[f[x][i]]>=dep[y])
			x = f[x][i];
	if(x == y) return x;
	for(int i=20; ~i; i--)
		if(f[x][i] ^ f[y][i])
			x=f[x][i], y=f[y][i];
	return f[x][0];
}

void build(int x){
	int lcaf = fa[x][0];
	for(int i=1; i<fa[x].size(); i++)
		lcaf = lca(lcaf, fa[x][i]);
	t[lcaf].push_back(x);
	dep[x] = dep[lcaf] + 1;
	f[x][0] = lcaf;
	for(int i=1; i<=20; i++)
		f[x][i] = f[f[x][i-1]][i-1];
}

void tp_sort(){
	queue <int> Q;
	for(int i=1; i<=n; i++)
		if(!in[i]){
			in[i]++;
			v[0].push_back(i);
			fa[i].push_back(0);
		}
	Q.push(0);
	while(!Q.empty()){
		int q = Q.front();
		Q.pop();
		tp[cnt++] = q;
		for(auto i : v[q]){
			in[i]--;
			if(!in[i]){
				Q.push(i);
				build(i);
			}
		}
	}
}

void init(){
	cnt = 0;
	for(int i=0; i<maxn; i++){
		in[i] = dep[i] = 0;
		v[i].clear();
		fa[i].clear();
		t[i].clear();
	}
}

int main() {
	scanf("%d", &T);
	while(T--){
		init();
		scanf("%d%d", &n, &m);
		for(int i=0, x, y; i<m; i++){
			scanf("%d%d", &y, &x);
			v[x].push_back(y);
			fa[y].push_back(x);
			in[y]++;
		}
		tp_sort();
		scanf("%d", &q);
		while(q--){
			int x, y, ans = 0;
			scanf("%d%d", &x, &y);
			int lcaf = lca(x, y);
			ans = dep[x] + dep[y] - dep[lcaf];
			printf("%d\n", ans);
		}
	}
}
Published 221 original articles · won praise 220 · views 20000 +

Guess you like

Origin blog.csdn.net/Scar_Halo/article/details/102809913