[树直径] [POJ] CowMarathon

时间复杂度超高

#pragma GCC optimize(2)
#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <cctype>
#include <string>
#include <cstring>
#include <algorithm>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <ctime>
#include <vector>
#include <fstream>
#include <list>
#include <iomanip>
#include <numeric>
using namespace std;
typedef long long ll;
 
const int MAXN = 1e6 + 10;
 
bool used[MAXN] = {0};
 
vector < pair <int, int> > arr[MAXN];
 
int lma, lmp, lb = 0, beg;
 
void findpoint(int now, int step)
{
    if(!used[now])
        used[now] = true;
    else
        return;   
    if(step > lma)
        lma = step, lmp = now;
    for(unsigned int i = 0; i < arr[now].size(); i++)
    {
        findpoint(arr[now][i].first, step + arr[now][i].second);
    }
}
 
void largeway(int now, int step)
{
    if(!used[now])
        used[now] = true;
    else
        return ;
    if(step > lb)
        lb = step;
    for(unsigned int i = 0; i < arr[now].size(); i++)
    {
        largeway(arr[now][i].first, step + arr[now][i].second);
    }
}

void init(int x, int y, int z)
{
    beg = x;
    arr[x].push_back(make_pair(y, z)), arr[y].push_back(make_pair(x, z));
}

int main()
{
    ios::sync_with_stdio(false);
 
    cin.tie(0);     cout.tie(0);
 
    int N, M;
 
    cin>>M>>N;
 
    while(N--)
    {
        int x, y, z;
        char c;
        cin>>x>>y>>z>>c;
        init(x, y, z);
    }

    memset(used, 0, sizeof(used));
    
    lma = 0, lmp = beg;
    
    findpoint(beg, 0);
    
    memset(used, 0, sizeof(used));
    
    largeway(lmp, 0);
 
    cout<<lb<<endl;
 
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Zeolim/article/details/82468112