Codeforces edu 7 E. Ants in Leaves 图论 搜索

题目

题目链接:http://codeforces.com/contest/622/problem/E

题目来源:Educational Codeforces Round 7

简要题意:蚂蚁从树的叶子上去根,两只蚂蚁不能同时在一个点,求最短的全到根的时间。

题解

去dfs和根相连的点,取出叶子然后根据深度排序。

假设所需的时间为 ai ,各个点深度为 di

ai+1=max(ai+1,di+1)

ai+1 就是由于 i+1 这点更深,假设令序号前的先爬,则由于要跟在后边出来需要增一。

深度则不必多说。

代码

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

#define pb push_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define sz(x) ((int)(x).size())
#define fi first
#define se second
using namespace std;
typedef long long LL;
typedef vector<int> VI;
typedef pair<int,int> PII;
LL powmod(LL a,LL b, LL MOD) {LL res=1;a%=MOD;for(;b;b>>=1){if(b&1)res=res*a%MOD;a=a*a%MOD;}return res;}
// head
const int N = 5e5+5;
const int M = N<<1;

struct Edge {
    int to, nxt;
    Edge(int to, int nxt) : to(to), nxt(nxt){}
    Edge() {}
};

int head[N];
Edge e[M];

void addEdge(int from, int to, int cnt) {
    e[cnt] = Edge(to, head[from]);
    head[from] = cnt;
}

void init(int n) {
    for (int i = 0; i <= n; i++) head[i] = -1;
}

VI leaf;

void dfs(int x, int fa, int d) {
    int cnt = 0;
    for (int i = head[x]; ~i; i = e[i].nxt) {
        int to = e[i].to;
        if (to == fa) continue;
        cnt++;
        dfs(to, x, d+1);
    }
    if (!cnt) leaf.pb(d);
}

int main()
{
    int n, u, v, ec = 0;
    scanf("%d", &n);
    init(n);
    for (int i = 1; i < n; i++) {
        scanf("%d%d", &u, &v);
        addEdge(u, v, ec++);
        addEdge(v, u, ec++);
    }

    int ans = 0;
    for (int i = head[1]; ~i; i = e[i].nxt) {
        dfs(e[i].to, 1, 0);
        sort(all(leaf));
        int cnt = leaf.size();
        for (int j = 0; j < cnt; j++) {
            ans = max(ans, leaf[j] + cnt - j);
        }
        leaf.clear();
    }
    printf("%d\n", ans);
    return 0;
}

你可能感兴趣的:(图论,搜索)