题目链接:http://codeforces.com/contest/979/problem/C
Kuro is living in a country called Uberland, consisting of (v,u)).
Oddly, there are 2 special towns in Uberland named Flowrisa (denoted with the index v, he reaches Beetopia after he reached Flowrisa, since the bees will be attracted with the flower smell on Kuro’s body and sting him.
Kuro wants to know how many pair of city (u,v) he can take as his route. Since he’s not really bright, he asked you to help him with this problem.
Input
The first line contains three integers x≠y) - the number of towns, index of the town Flowrisa and index of the town Beetopia, respectively.
b.
It is guaranteed that from each town, we can reach every other town in the city using the given roads. That is, the given map of towns and roads is a tree.
Output
A single integer resembles the number of pair of towns (u,v) that Kuro can use as his walking route.
input
3 1 3
1 2
2 3
output
5
On the first example, Kuro can choose these pairs:
- 1→2,
- 2→3,
- 3→2,
- 2→1,
- 3→2→1.
Kuro can't choose pair (3,1) is still allowed because although Kuro visited Flowrisa and Beetopia, he did not visit them in that order).
题意
无向图,n个点,n-1条边,每两个点都可以到达,但是从依次经过u,v两点的道路不能走,问有多少个x->y可以到达
思路
ans = 总路线条数 - u到v的路线数。u到v路线数 = u端的点数*v端的点数。判断点数用dfs。或者用SPFA记录u到v的所有点,再分别dfs u 和 v
#include <bits/stdc++.h> using namespace std; typedef long long LL; const int N = 3e5+4; bool vis[N]; LL n, ans1 = 0, ans2 = 0, u, v, pre; vector<int>V[N]; void dfs1(LL s, LL x) { vis[s] = 1; if(s == v) { pre = x; return; } ans1++; for(LL i = 0; i < V[s].size(); i++) { LL k = V[s][i]; if(vis[k]) continue; dfs1(k, s); } } void dfs2(int s) { vis[s] = 1; if(s == u || s == v) return; ans2++; for(LL i = 0; i < V[s].size(); i++) { LL k = V[s][i]; if(vis[k]) continue; dfs2(k); } } int main() { LL a, b; scanf("%lld%lld%lld", &n, &u, &v); for(LL i = 1; i < n; i++) { scanf("%lld%lld", &a, &b); V[a].push_back(b); V[b].push_back(a); } dfs1(u, u); memset(vis, 0, sizeof vis); dfs2(pre); printf("%lld\n", n*(n-1)-(ans1-ans2)*(n-ans1)); return 0; }