[HihoCoder]#1050 : 树中的最长路

来源:互联网 发布:python接口测试脚本 编辑:程序博客网 时间:2024/05/23 19:00

华电北风吹
天津大学认知计算与应用重点实验室
2016-06-24

题目链接:
http://hihocoder.com/problemset/problem/1050

题目分析:
知道树中最长路的性质即可。

// problem1050.cpp : 定义控制台应用程序的入口点。// #1050 : 树中的最长路// 张正义 2016-05-15#include "stdafx.h"#include <iostream>#include <vector>#include <queue>using namespace std;int BroadVisit(vector<vector<int>> &edgeList, int start, int &end){    int depth = -1;    queue<int> q;    vector<bool> visited(edgeList.size());    q.push(-1);    q.push(start);    while (q.empty()==false)    {        if (q.front() == -1)        {            q.pop();            q.push(-1);            if (q.front() == -1)            {                break;            }            depth++;        }        int nodeNum = q.front();        q.pop();        visited[nodeNum] = true;        for (int i = 0; i < edgeList[nodeNum].size(); i++)        {            if (visited[edgeList[nodeNum][i]] == false)            {                end = edgeList[nodeNum][i];                q.push(end);            }        }    }    return depth;}int main(){    int n;    cin >> n;    vector<vector<int>> edgeList(n);    for (int i = 0; i < n - 1; i++)    {        int p1, p2;        cin >> p1 >> p2;        p1--; p2--;        edgeList[p1].push_back(p2);        edgeList[p2].push_back(p1);    }    int end;    BroadVisit(edgeList, 0, end);    cout << BroadVisit(edgeList, end, end) << endl;    return 0;}

解题报告:
第一次做的时候不知道规律,知道后就简单了。

0 0
原创粉丝点击