UVALive3902-Network(dfs)

题目链接

http://vjudge.net/problem/UVALive-3902

思路

先无根树转有根树,然后可以贪心
对于深度大于k的节点,选择深度最深的节点,向上走k步走到节点A,那么将节点A作为一个新的server一定是最优解,然后删去以节点A为根的子树,继续上述过程

代码

#include <iostream>
#include <cstring>
#include <stack>
#include <vector>
#include <set>
#include <map>
#include <cmath>
#include <queue>
#include <sstream>
#include <iomanip>
#include <fstream>
#include <cstdio>
#include <cstdlib>
#include <climits>
#include <deque>
#include <bitset>
#include <algorithm>
using namespace std;

#define PI acos(-1.0)
#define LL long long
#define PII pair<int, int>
#define PLL pair<LL, LL>
#define mp make_pair
#define IN freopen("in.txt", "r", stdin)
#define OUT freopen("out.txt", "wb", stdout)
#define scan(x) scanf("%d", &x)
#define scan2(x, y) scanf("%d%d", &x, &y)
#define scan3(x, y, z) scanf("%d%d%d", &x, &y, &z)
#define sqr(x) (x) * (x)

const int maxn = 1005;
int n, s, k;
vector<int> G[maxn];
vector<int> node[maxn];
int fa[maxn], deep[maxn], vis[maxn];

void init() {
    for (int i = 0; i < maxn; i++) {
        G[i].clear();
        node[i].clear();
    }
    memset(vis, 0, sizeof(vis));
}

void dfs(int u, int f, int d) {
    if (G[u].size() == 1 && d > k) {
        node[d].push_back(u);
    }
    for (int i = 0; i < G[u].size(); i++) {
        int v = G[u][i];
        if (v == f || v == -1) continue;
        fa[v] = u;
        deep[v] = d;
        dfs(v, u, d + 1);
    }
}

void dfs2(int u, int f, int d) {
    vis[u] = 1;
    for (int i = 0; i < G[u].size(); i++) {
        int v = G[u][i];
        if (v == f) continue;
        if (d < k) {
            dfs2(v, u, d + 1);
        }
    }
}

int solve() {
    int cnt = 0;
    for (int d = n - 1; d > k; d--) {
        for (int i = 0; i < node[d].size(); i++) {
            int u = node[d][i];
            if (vis[u]) continue;
            for (int j = 0; j < k; j++) {
                u = fa[u];
            }
            cnt++;
            dfs2(u, -1, 0);
        }
    }
    return cnt;
}

int main() {
    int T;
    scan(T);
    while (T--) {
        init();
        scan(n);
        scan2(s, k);
        for (int i = 0; i < n - 1; i++) {
            int x, y;
            scan2(x, y);
            G[x].push_back(y);
            G[y].push_back(x);
        }
        dfs(s, -1, 0);
        printf("%d\n", solve());
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值