• 旅游规划--信息学一本通


    bfs第一次写崩了,超时到怀疑人生

    #include<cstdio>
    #include<iostream>
    #include<algorithm>
    #include<cstring>
    #include<vector>
    #include<queue>
    #define maxn 200010
    using namespace std;
    vector<int>G[maxn];
    void insert(int be, int en) {
        G[be].push_back(en);
    }
    int n;
    int dis1[maxn];
    int dis2[maxn];
    int vis[maxn];
     
    int dfs1(int x, int fa, int dp) {//求直径
        dis1[x] = dp;
        for (int i = 0; i < G[x].size(); i++) {
            int p = G[x][i];
            if (p == fa) continue;
             
            dfs1(p, x, dp + 1);
        }
        return 0;
    }
     
    int bfs(int be,int *dis) {                  //标记层数
        queue<int>que;
        que.push(be);
        dis1[be] = -1;
        while (!que.empty()) {
            int x = que.front();
            que.pop();
            for (int i = 0; i < G[x].size(); i++) {
                int p = G[x][i];
                if (!vis[p]) {
                    vis[p] = 1;
                    dis[p] = dis[x] + 1;
                    que.push(p);
                }
            }
        }
        return 0;
    }
    int dfs(int x,int fa) {
        for (int i = 0; i < G[x].size(); i++) {
            int p = G[x][i];
            if (p == fa) continue;
            if (dis1[p] > dis1[x]) {
                dfs(p, x);
                dis2[x] = max(dis2[x], dis2[p] + 1);
            }
        }
        return 0;
    }
    int main() {
        int be, en;
        scanf("%d", &n);
        for (int i = 1; i < n; i++) {
            scanf("%d %d", &be, &en);
            insert(be, en);
            insert(en, be);
        }
        dfs1(1, -1, 0);
        int s=0, t=0;
        int len = 0;
        for (int i = 0; i < n; i++) {
            if (dis1[s] < dis1[i]) {
                s = i;
                len = dis1[i];
            }
        }
        memset(dis1, 0, sizeof(dis1));
        dfs1(s, -1, 0);
        for (int i = 0; i < n; i++) {
            len = max(dis1[i], len);            //获得直径
        }
     
        for (int i = 0; i < n; i++) {            //把一端直径捆起来
            if (dis1[i] == len) {
                insert(n, i);
                insert(i, n);
            }
        }
        bfs(n, dis1);
        for (int i = 0; i < n; i++) {
            if (dis1[i] == len) {
                insert(n + 1, i);
                insert(i, n + 1);
            }
        }
        memset(vis, 0, sizeof(vis));
        bfs(n + 1, dis2);
        for (int i = 0; i < n; i++) {
            if (dis1[i] + dis2[i] == len + 1) {
                printf("%d
    ", i);
            }
        }
        return 0;
    }
    

      

    寻找真正的热爱
  • 相关阅读:
    Google Maps Android API v2 开发笔记
    eclipse快捷键设置
    浮动div,回到顶部
    android开发环境
    Android百度地图开发之地址解析MKSearch.geocode()
    java基础(for循环)
    博客园首记
    记录有待阅读的文章——2013.2.2
    整理推荐的CSS属性书写顺序
    JavaScript——Firebug控制台详解
  • 原文地址:https://www.cnblogs.com/lesning/p/11735353.html
Copyright © 2020-2023  润新知