Tree Problem---容斥,dfs

任意门
You are given a tree consisting of n vertices. Recall that a tree is a connected graph consisting of n vertices and (n−1) undirected edges.

Now, your task is to answer q queries. Each query will give you a vertex x, please calculate the number of simple paths of length at least one through the vertex x. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths). For example, paths [1,2,3] and [3,2,1] are considered the same.

Recall that a simple path is a path that visits each vertex at most once.

Input
The first line contains an integer n (2≤n≤105) indicating the number of vertices.

For the next (n−1) lines, the i-th line contains two integers ui and vi (1≤ui,vi≤n) indicating an edge connecting vertices ui and vi in the tree.

The first line contains an integer q (1≤q≤105) indicating the number of queries.

For the next q lines, the i-th line contains an integer xi (1≤xi≤n) indicating the vertex as described above.

Output
For each query output one line containing one integer indicating the answer.

inputCopy

5
1 2
1 3
3 4
3 5
5
1
2
3
4
5

output

7
4
9
4
4

在这里插入图片描述

#include<iostream>
#include<cmath>
#include<cstring>
#include<cstdio>
#include<algorithm>
using namespace std;

#define int long long

const int maxn = 1010000;
int n;
int q;
int tot;
int head[maxn];//head数组可以理解成表头它记录了它第一条边的的坐标
int siz[maxn];
int fa[maxn];
int cnt[maxn];

struct edge{
    int to;
    int from;
    int nxt;//记录他的下一条边
}e[2*maxn];

void add(int x, int y){
    tot++;
    e[tot].to = y;
    e[tot].from = x;
    e[tot].nxt = head[x];
    head[x] = tot;
}

void dfs(int x, int f){
    fa[x] = f;
    siz[x] = 1;
    long long now = 0;
    for(int i = head[x]; i; i = e[i].nxt){
        int y = e[i].to;
        if(y == f) continue;
        dfs(y, x);
        siz[x] += siz[y];//记录下他联结的子树的点的个数
        now += siz[y] * siz[y];//在同一子树里面任选两个点的路径
    }
    now += (n - siz[x]) * (n - siz[x]);//在不同子树中任选两个点的路径
    //这里运用到了容斥,任选两个点(除了他自己以外)的路径减去不经过他的路径等于经过他的路径
    cnt[x] += ((n - 1) * (n - 1) - now) / 2;
}

signed main(){
    scanf("%lld",&n);
    int x, y;
    for(int i = 1; i < n; i++){
        // cin >> x >> y;
        scanf("%lld %lld", &x, &y);
        add(x, y);
        add(y, x);
    }
    dfs(1, 0);
    cin >> q;
    long long ans = 0;
    for(int k = 1; k <= q; k++){
        // cin >> x;
        scanf("%lld", &x);
        printf("%lld\n",cnt[x] + n - 1);//以自己为其中一个点,共有n-1种情况
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值