csp 201503-4 网络延时

一开始想着要写lca,后来发现剪枝后还是超时

后来发现其实就是求树的直径问题;

求树的直径:

1.dp

2.两次bfs

第一次求离根最远的点

第二次求离根最远的点的最远的点

#include<bits/stdc++.h>
using namespace std;
#define maxn 20010

struct node
{
   int pos;
   int h;
};

vector<int> E[maxn];
bool vis[maxn];
int n,m;
int k,dep;

void addedge(int u,int v)
{
    E[u].push_back(v);
    E[v].push_back(u);
}

void bfs(int st)
{
    k=-1;
    dep=0;
    memset(vis,false,sizeof vis);
    node a;
    a.pos=st;
    a.h=0;
    queue<node> q;
    q.push(a);
    vis[st]=true;
    node t;
    while(!q.empty())
    {
        t=q.front();
        q.pop();
        int u=t.pos;
        int h=t.h;
        for(int i=0;i<E[u].size();i++)
        {
            int v=E[u][i];
            if(!vis[v])
            {
                node tmp;
                tmp.pos=v;
                tmp.h=h+1;
                q.push(tmp);
                vis[v]=true;
                if(h+1>dep)
                {
                    dep=h+1;
                    k=v;
                }
            }
        }
    }
}


int main()
{
    cin>>n>>m;
    for(int i=2;i<=n;i++)
    {
        int t;
        cin>>t;
        addedge(i,t);
    }
    for(int i=1+n;i<=m+n;i++)
    {
        int t;
        cin>>t;
        addedge(i,t);
    }
    bfs(1);
    bfs(k);
    cout<<dep<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/hzaukotete/article/details/84991091
今日推荐