[暴搜] 树直径

无向无环图

求最远两元素距离

暴力搜索

1.任取点穷举最远

2.得点再穷举最远

//#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 <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], step + 1);
    }
}
 
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], step + 1);
    }
}

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

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

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

猜你喜欢

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