1. 程式人生 > 其它 >【學軍NOIP開放題2-B】託薩妮婭(樹)(dfs)

【學軍NOIP開放題2-B】託薩妮婭(樹)(dfs)

給你 k 個 n 個點的樹。 然後問你對於每一對點,有多少個點存在於每個樹中這一對點的路徑上。

託薩妮婭

題目連結:學軍NOIP開放題2-B

題目大意

給你 k 個 n 個點的樹。
然後問你對於每一對點,有多少個點存在於每個樹中這一對點的路徑上。

思路

考慮用這麼一個性質:
\(dis_{x,y}\leqslant dis_{x,z}+dis_{z,k}\),等號成立當且僅當 \(z\)\(x,y\) 的路徑上。

那要每個圖都滿足,就是要 \(\sum dis_{x,y}=\sum dis_{x,z}+\sum dis_{z,k}\)

那我們就可以求出每個圖任意兩點之間的距離,然後就可以暴力判斷了。

然後求距離可以直接列舉 \(x\) 然後 dfs。

程式碼

#include<cstdio>
#include<iostream>
#define ll long long

using namespace std;

int n, k, x, y, all_dis[501][501];
ll ans;
struct node {
	int to, nxt;
};
struct Graph {
	node e[1001];
	int le[501], KK, deg[501];
	
	void add(int x, int y) {
		e[++KK] = (node){y, le[x]}; le[x] = KK;
		e[++KK] = (node){x, le[y]}; le[y] = KK;
	}
	
	void dfs(int st, int now, int father) {
		all_dis[st][now] += deg[now];
		for (int i = le[now]; i; i = e[i].nxt)
			if (e[i].to != father) {
				deg[e[i].to] = deg[now] + 1;
				dfs(st, e[i].to, now);
			}
	}
}g[501];

int main() {
//	freopen("tosania.in", "r", stdin);
//	freopen("tosania.out", "w", stdout);
	
	scanf("%d %d", &n, &k);
	for (int i = 1; i <= k; i++) {
		for (int j = 1; j < n; j++) {
			scanf("%d %d", &x, &y);
			g[i].add(x, y);
		}
	}
	
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= n; j++) {
			g[i].deg[j] = 0;
			g[i].dfs(j, j, 0);
		}
	}
	
	for (int i = 1; i <= n; i++) {
		ans = 0;
		for (int j = 1; j <= n; j++) {
			for (int k = 1; k <= n; k++)
				if (all_dis[i][j] == all_dis[i][k] + all_dis[k][j]) {
					ans = ans + j;
				}
		}
		printf("%lld\n", ans);
	}
	
	return 0;
}