CF 1029E Tree with Small Distances

昨晚随便玩玩搞个div3结果浪翻了……

强烈谴责D题hack数据卡常

考虑到本题中所要求的最短距离不会大于2,所以我们可以把所有结点到$1$的距离通过对$3$取模分类,考虑到直接自顶向下贪心不满足局部最优解可以推出全局最优解,所以我们可以自下向上这样可以考虑到所有条件。我们处理出一个结点$x$所有儿子$y$的取模后的距离的最小值$dis$,那么一个结点向$1$连一条边的充要条件就是:

$dis == 0 && x != 1 && fa != 1$

时间复杂度$O(n)$。

Code:

#include <cstdio>
#include <cstring>
using namespace std;

const int N = 2e5 + 5;

int n, ans = 0, tot = 0, head[N];

struct Edge {
    int to, nxt;
} e[N << 1];

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

inline void read(int &X) {
    X = 0;
    char ch = 0;
    int op = 1;
    for(; ch > '9'|| ch < '0'; ch = getchar())
        if(ch == '-') op = -1;
    for(; ch >= '0' && ch <= '9'; ch = getchar())
        X = (X << 3) + (X << 1) + ch - 48;
    X *= op;
}

inline void chkMin(int &x, int y) {
    if(y < x) x = y;
}

int dfs(int x, int fat) {
    int dis = 2;
    for(int i = head[x]; i; i = e[i].nxt) {
        int y = e[i].to;
        if(y == fat) continue;
        chkMin(dis, dfs(y, x));
    }
    
    if(dis == 0 && x != 1 && fat != 1) ans++;
    return (dis + 1) % 3;
}

int main() {
    read(n);
    for(int x, y, i = 1; i < n; i++) {
        read(x), read(y);
        add(x, y), add(y, x);
    }
    dfs(1, 0);
    printf("%d\n", ans);
    return 0;
}
View Code

 

转载于:https://www.cnblogs.com/CzxingcHen/p/9532801.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值