C. Kuro and Walking Route
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

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.

Examples
input
Copy
3 1 3
1 2
2 3
output
Copy
5
input
Copy
3 1 3
1 2
1 3
output
Copy
4
Note

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).

On the second example, Kuro can choose the following pairs:

  • 1→2,
  • 2→1,
  • 3→1→2,
  • 3→1.
#include<cmath>
#include<queue>
#include<cstdio>
#include<string.h>
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
const int INF=0x3f3f3f3f;
const int N=3e5+10;
vector<int> g[N];
int num[N];
int par[N];
int n,x,y;
int dfs(int u,int fa){
    par[u]=fa;
    int cnt=0;
    for(int v:g[u]){
        if(v!=fa){
            cnt+=dfs(v,u);
        }
    }
    return num[u]=cnt+1;
}
int main() {
    scanf("%d%d%d",&n,&x,&y);
    for(int i=0;i<n-1;i++){
        int u,v;
        scanf("%d%d",&u,&v);
                g[u].push_back(v);
                g[v].push_back(u);
    }
    dfs(x,-1);
    long long ans=0;
    int m=y;
    while(par[m] !=x){
        m=par[m];
    }
    ans=(long long )n*(n-1);
    ans-=(long long )num[y]*(n-num[m]);
    printf("%lld\n",ans);
    return 0;
}
View Code

 

相关文章: