闇の連鎖问题

分析可知, 这里就是要砍两条边, 第一次看主要边, 第二次砍附加边, 主要边就是树边, 附加边就是非树边, 假设非树边连接为 点 x , y x,y x,y,当删除一条 x , y x,y x,y 之间的树边后, 非树边就成为了树边, 如果当 x , y x,y x,y 之间的数量为 s s s, 当 s = 0 s = 0 s=0 时, 删去任意一条非树边即可, 当 s = 1 s = 1 s=1 时, 必须要砍去x,y之间的非树边,当 s > 1 s > 1 s>1,无解

然后这里边的覆盖需要利用到区间的加减, 即差分,

#include<bits/stdc++.h>

using namespace std;

const int N = 1e5 + 10, M = 2 * N;

int e[M], ne[M], h[N], idx, depth[N], fa[N][17], ans, n, m, d[N];

void add(int a, int b)
{
    e[idx] = b, ne[idx] = h[a], h[a] = idx ++;
}

void bfs()   //预处理
{
    memset(depth, 0x3f, sizeof depth);
    
    depth[0] = 0, depth[1] = 1;
    
    queue<int>q;
    q.push(1);
    
    while(q.size())
    {
        auto t = q.front();
        q.pop();
        
        for(int i = h[t]; ~i; i = ne[i])
        {
            int j = e[i];
            if(depth[j] > depth[t] + 1)
            {
                depth[j] = depth[t] + 1;
                q.push(j);
                
                fa[j][0] = t;
                
                for(int k = 1; k <= 16; k ++ )
                fa[j][k] = fa[fa[j][k - 1]][k - 1];
            }
        }
    }
}

int lca(int a, int b)   //lca模板
{
    if(depth[a] < depth[b]) swap(a, b);
    
    for(int i = 16; i >= 0; i -- ) 
    if(depth[fa[a][i]] >= depth[b]) a = fa[a][i];
    
    if(a == b) return a;
    for(int i = 16; i >= 0; i -- )
    if(fa[a][i] != fa[b][i]) a = fa[a][i], b = fa[b][i];
    
    return fa[a][0];
}
int  dfs(int u, int fa)
{
    int res = d[u];   //记录当前覆盖附加边的数量
    
    for(int i = h[u]; ~i; i = ne[i])
    {
        int j = e[i];
        if(j == fa) continue;
        int s = dfs(j, u);
        if(s == 0) ans += m;   //该路径上没有覆盖附加边, 
        else if(s == 1) ans ++;   //  覆盖了一条附加边
        res += s;   //更新附加边的数量                                                                      
    }
    return res;
}


int main()
{
    cin >> n >> m;
    
    memset(h, -1, sizeof h);   //初始化表头
     
    for(int i = 1; i <= n - 1; i ++ )  //建图
    {
        int a, b, c;
        cin >> a >> b;
        add(a, b), add(b, a);
    }
    
    bfs();   //预处理 fa数组, depth数组
    
    for(int i = 1; i <= m; i ++ )
    {
        int a, b;
        cin >> a >> b;
        d[a] ++, d[b] ++, d[lca(a, b)] -= 2;   //树上差分
    }
    
    dfs(1, -1);   //计算
    
    cout << ans << '\n';
}
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

广西小蒟蒻

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值