大臣的旅费(树的直径)

windows+shift+s不能截图了,百度了也没解决,起床再说吧,留着以后做板子

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <queue>
using namespace std;
const int maxn = 1000 + 01;
const int maxm = 10002 + 10;
struct Edge
{
    int before;
    int to;
    int w;
} e[maxm];
int n, x, y, z, k, head[maxn], dis[maxn], vis[maxn];
void add(int u, int v, int w)
{
    e[k].to = v;
    e[k].w = w;
    e[k].before = head[u];
    head[u] = k++;
}
int bfs(int s, int &target)
{
    memset(dis, 0, sizeof dis);
    memset(vis, 0, sizeof vis);
    queue<int> q;
    q.push(s);
    dis[s] = 0;
    vis[s] = 1;
    int max_dis = -9;
    while (!q.empty())
    {
        int u = q.front();
        q.pop();
        if (dis[u] > max_dis)
        {
            max_dis = dis[u];
            target = u;
        }
        for (int i = head[u]; i != -1; i = e[i].before)
        {
            int v = e[i].to;
            if (dis[v] == 0 && vis[v] == 0)
            {
                vis[v] = 1; //防止回到起点 
                dis[v] = dis[u] + e[i].w;
                q.push(v);
            }
        }
    }
    return max_dis;
}
void solve()
{
    int target, p;
    bfs(1, target);
    int t = bfs(target, p);
    cout << t * (t + 1) / 2 + 10 * t;
}
int main()
{
    cin >> n;
    k = 0;
    memset(head, -1, sizeof head);
    for (int i = 0; i < n - 1; i++)
    {
        cin >> x >> y >> z;
        add(x, y, z);
        add(y, x, z);
    }
    solve();
    return 0;
}
发布了51 篇原创文章 · 获赞 21 · 访问量 3075

猜你喜欢

转载自blog.csdn.net/qq_44115065/article/details/103966337