码迷,mamicode.com
首页 > 其他好文 > 详细

CF 1029E Tree with Small Distances

时间:2018-08-25 11:24:57      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:display   时间   hack   通过   直接   分类   none   str   min   

昨晚随便玩玩搞个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

 

CF 1029E Tree with Small Distances

标签:display   时间   hack   通过   直接   分类   none   str   min   

原文地址:https://www.cnblogs.com/CzxingcHen/p/9532801.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!