AcWing 325. 计算机 经典树的直径

一所学校前一段时间买了第一台计算机(所以这台计算机的ID是1)。

近年来,学校又购买了N-1台新计算机。

每台新计算机都与之前买进的计算机中的一台建立连接。

现在请你求出第i台计算机到距离其最远的计算机的电缆长度。
在这里插入图片描述

例如,上图中距离计算机1最远的是计算机4,因此 S1=3;距离计算机2最远的是计算机4和5,因此 S2=2;距离计算机3最远的是计算机5,所以 S3=3;同理,我们也得到 S4=4,S5=4


输入格式

输入包含多测试数据。

每组测试数据第一行包含整数N。

接下来N-1行,每行包含两个整数,第 i 行的第一个整数表示第 i 台电脑买入时连接的电脑编号,第二个整数表示这次连接花费的电缆长度。
输出格式

每组测试数据输出N行。

第 i 行输出第 i 台电脑的 Si


数据范围

1≤N≤10000
,
电缆总长度不超过109

输入样例:

5
1 1
2 1
3 1
1 1

输出样例:

3
2
3
4
4


  • n台计算机连成一棵树,每条边有边权,对于每个点u都有一个离u最远的点v,对于每个点打印距离Dist(u, v)
  • 先求树的直径 (端点为 U 和 V ) 两次dfs
    • 先任选一个点为rootdfs到最远点记为U
    • 再从U开始dfs到最远点记为V,则U到V一定是直径
  • 则,任意一个点的最远点一定是直径两个端点的其中一个U 或 V

c++

#define debug
#ifdef debug
#include <time.h>
#endif

#include <iostream>
#include <algorithm>
#include <vector>
#include <string.h>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <math.h>

#define MAXN ((int)1e5+7)
#define ll long long int
#define INF (0x7f7f7f7f)
#define fori(lef, rig) for(int i=lef; i<=rig; i++)
#define forj(lef, rig) for(int j=lef; j<=rig; j++)
#define fork(lef, rig) for(int k=lef; k<=rig; k++)
#define QAQ (0)

using namespace std;

#define show(x...) \
    do { \
       cout << "\033[31;1m " << #x << " -> "; \
       err(x); \
    } while (0)

void err() { cout << "\033[39;0m" << endl; }
template<typename T, typename... A>
void err(T a, A... x) { cout << a << ' '; err(x...); }

namespace FastIO{

    char print_f[105];
    void read() {}
    void print() { putchar('\n'); }

    template <typename T, typename... T2>
       inline void read(T &x, T2 &... oth) {
           x = 0;
           char ch = getchar();
           ll f = 1;
           while (!isdigit(ch)) {
               if (ch == '-') f *= -1; 
               ch = getchar();
           }
           while (isdigit(ch)) {
               x = x * 10 + ch - 48;
               ch = getchar();
           }
           x *= f;
           read(oth...);
       }
    template <typename T, typename... T2>
       inline void print(T x, T2... oth) {
           ll p3=-1;
           if(x<0) putchar('-'), x=-x;
           do{
                print_f[++p3] = x%10 + 48;
           } while(x/=10);
           while(p3>=0) putchar(print_f[p3--]);
           putchar(' ');
           print(oth...);
       }
} // namespace FastIO
using FastIO::print;
using FastIO::read;

int n, m, Q, K;

struct Edge {
    int v, w;
    bool operator < (const Edge& no) const { return w < no.w; }
} ;

vector<Edge> G[MAXN];

int U, V, tmax;
void dfs1(int u, int fa, int level) {
    // show(u);
    if(tmax <= level) {
        tmax = level;
        U = u;
    }
    for(auto ed : G[u]) {
        int v = ed.v, w = ed.w;
        if(fa != v) dfs1(v, u, level+w);

    }
}

void dfs2(int u, int fa, int level) {
    if(tmax <= level) {
        tmax = level;
        V = u;
    }
    for(auto ed : G[u]) {
        int v = ed.v, w = ed.w;
        if(fa != v) dfs2(v, u, level+w);
    }
}

int depU[MAXN], depV[MAXN];

void dfs(int u, int fa, int level, int* ptr) {
    ptr[u] = level;
    for(auto ed : G[u]) {
        int v = ed.v, w = ed.w;
        if(fa != v) dfs(v, u, level+w, ptr);
    }
}

signed main() {
#ifdef debug
    freopen("test.txt", "r", stdin);
    clock_t stime = clock();
#endif
    // read(n);
    while(~scanf("%d ", &n)) {
        U = V = tmax = 0;
        #define cls(x) (memset(x, 0, sizeof(x)))
        cls(depU), cls(depV);
        for(int i=0; i<=n; i++) G[i].clear();
        int u, w;
        for(int i=2; i<=n; i++) {
            read(u, w);
            G[u].push_back({i, w}), G[i].push_back({u, w});
        }

        dfs1(1, 1, 0);
        tmax = 0;
        dfs2(U, U, 0);
        dfs(U, U, 0, depU), dfs(V, V, 0, depV);
        for(int i=1; i<=n; i++)
            printf("%d\n", max(depU[i], depV[i]));
    }



#ifdef debug
   clock_t etime = clock();
   printf("rum time: %lf 秒\n",(double) (etime-stime)/CLOCKS_PER_SEC);
#endif 
   return 0;
}



java


import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;

class Edge {
    int v, w;

    public Edge() { }

    public Edge(int v, int w) {
        this.v = v;
        this.w = w;
    }
}

public class Main {
    public static final boolean debug = true;
    public static String INPATH = "C:\\Users\\majiao\\Desktop\\test.txt",
            OUTPATH = "C:\\Users\\majiao\\Desktop\\out.txt";
    public static StreamTokenizer tok;
    public static BufferedReader cin;
    public static PrintWriter cout;

    public static long start_time = 0, out_time = 0;
    public static int n, m, K, Q, MAXN = (int)1e5+7, INF = 0x3f3f3f3f, tmax = 0, U = 0, V = 0;
    static int depU[] = new int[MAXN], depV[] = new int[MAXN];
    public static byte buf[] = new byte[MAXN];
    static ArrayList<Edge> G[] = new ArrayList[MAXN];

    public static void main(String[] args) throws IOException {
        main_init();
        if(debug) { start_time = System.currentTimeMillis(); }
        if(false) { System.setOut(new PrintStream(OUTPATH)); }

        int u = 0, w = 0;
        while((n=read_int()) != -1) {
            U = V = tmax = 0;
            for(int i=0; i<=n; i++) {
                if(null == G[i]) G[i] = new ArrayList<>();
                G[i].clear();
                depU[i] = depV[i] = 0;
            }
            for(int i=2; i<=n; i++) {
                u = read_int(); w = read_int();
                G[u].add(new Edge(i, w)); G[i].add(new Edge(u, w));
            }
            dfs1(1, 1, 0);
            tmax = 0;
            dfs2(U, U, 0);
            tmax = 0;
            dfs(U, U, 0, depU);
            dfs(V, V, 0, depV);
            for(int i=1; i<=n; i++)
                cout.println(Math.max(depU[i], depV[i]));
        }

        if(debug) {
            out_time = System.currentTimeMillis();
            cout.printf("run time : %d ms\n", out_time-start_time);
        }
        cout.flush();
    }

    static void dfs1(int u, int fa, int level) {
        if(tmax <= level) {
            tmax = level;
            U = u;
        }
        int sz = G[u].size();
        for(int i=0; i<sz; i++) {
            Edge ed = G[u].get(i);
            if(ed.v != fa) dfs1(ed.v, u, level+ed.w);
        }
    }

    static void dfs2(int u, int fa, int level) {
        if(tmax <= level) {
            tmax = level;
            V = u;
        }
        int sz = G[u].size();
        for(int i=0; i<sz; i++) {
            Edge ed = G[u].get(i);
            if(ed.v != fa) dfs2(ed.v, u, level+ed.w);
        }
    }

    static void dfs(int u, int fa, int level, int ptr[]) {
        ptr[u] = level;
        int sz = G[u].size();
        for(int i=0; i<sz; i++) {
            Edge ed = G[u].get(i);
            if(ed.v != fa) dfs(ed.v, u, level+ed.w, ptr);
        }
    }

    public static void main_init() {
        try {
            if (debug) {
                cin = new BufferedReader(new InputStreamReader(
                        new FileInputStream(INPATH)));
            } else {
                cin = new BufferedReader(new InputStreamReader(System.in));
            }
            cout = new PrintWriter(new OutputStreamWriter(System.out));
//            cout = new PrintWriter(OUTPATH);
            tok = new StreamTokenizer(cin);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String next_str() {
        try {
            tok.nextToken();
            if (tok.ttype == StreamTokenizer.TT_EOF)
                return null;
            else if (tok.ttype == StreamTokenizer.TT_NUMBER) {
                return String.valueOf((int)tok.nval);
            } else if (tok.ttype == StreamTokenizer.TT_WORD) {
                return tok.sval;
            } else return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static int read_int() {
        String tmp_next_str = next_str();
        return null==tmp_next_str ? -1 : Integer.parseInt(tmp_next_str);
    }
    public static long read_long() { return Long.parseLong(next_str()); }
    public static double read_double() { return Double.parseDouble(next_str()); }
    public static BigInteger read_big() { return new BigInteger(next_str()); }
    public static BigDecimal read_dec() { return new BigDecimal(next_str()); }

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值