【掩体计划——DFS+缩点】

题目

代码

cpp 复制代码
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
vector<vector<int>> g;
bool st[N];
int ans = 1e9;
bool dfs(int f, int u, int dis)
{
    bool is = 1;
    for (auto j : g[u])
    {
        if (j == f)
            continue;
        is &= dfs(u, j, dis + (g[u].size() > 2));
    }

    if (g[u].size() == 1) // 无向图叶子节点判定
        is = st[u];
    if (is)
        ans = min(ans, dis);
    return is;
}
int main()
{
    int n;
    cin >> n;

    g.resize(n + 1);
    for (int i = 1; i < n; i++)
    {
        int a, b;
        cin >> a >> b;
        g[a].push_back(b);
        g[b].push_back(a);
    }

    g[1].push_back(-1); // 为了统一那个多出来的父节点
    int m;
    cin >> m;
    for (int i = 1; i <= m; i++)
    {
        int x;
        cin >> x;
        st[x] = 1;
    }

    dfs(-1, 1, 0);

    cout << ans;
    return 0;
}
相关推荐
高晶10 分钟前
无乘法器实现LC二阶滤波器:基于移位运算的快速算法与四种精度推导
算法·设计模式·程序员
ysbfsy13 分钟前
大数计算思路
算法
高晶23 分钟前
主从自动分配算法:平均值乘以设备数一半的选举基准值解析
算法·设计模式·程序员
学电子她就能回来吗1 小时前
LeetCode Hot 100|普通数组专题学习笔记(零基础版)
笔记·算法·leetcode
用户老李1 小时前
反向传播计算梯度举例
算法
niyongsheng1 小时前
多智能体连续时间内路径规划:AA-SIPP(m) 的 Rust 实现与算法
算法·rust·机器人
302wanger2 小时前
DeepSeek-V4.1-Flash-1017 免费用到1024,速来
算法
lisw052 小时前
微分与积分的本质区别解析
算法·数学建模·极限编程
xys_6783 小时前
深挖数据结构:树和二叉树(上)
数据结构·算法
Interview Aid1123 小时前
Google SWE Intern VO 面经:两轮 Coding,Follow-up 考察 BFS 状态
算法