您的位置:首页 > 理论基础 > 数据结构算法

hihocoder 1050

2015-02-10 16:51 197 查看


        题意为求一棵树中的最长路径。这里采用两次BFS的办法。任选一个结点作为根结点, 记为A。以A为起点进行一次BFS,可以证明,最远路径的端点一定是离A最远的点。证明如下:
        若A是最远路径的一个端点,则距离A最远的点也一定是最远路径的端点;

        若A不是最远路径的端点,设一条最远路径为BC,A连接到BC之间的一点,假设BC都不是离A最远的点,设最远点为D,则可证明DB和DC均比BC长,矛盾。故最远路径的端点一定是离A最远的点。

        为了复习数据结构,简单写了个图的类,结果调试了好久……

// hiho 1050
// Find the length of the longest path in a tree
#include<iostream>
#include<cstdio>
#include<memory.h>
using namespace std;

class graph{
private:
struct edgeNode{
int end;
edgeNode* next;

edgeNode(int e, edgeNode* n = NULL): end(e), next(n) {}
edgeNode(): next(NULL) {}
};

struct verNode{
int vertex; // 有用吗
edgeNode* head;
int step;

verNode(int v, edgeNode* h = NULL): vertex(v), head(h), step(0) {}
verNode(): head(NULL), step(0) {}
};

verNode* table;
int vSize;

public:
graph(int v){
table = new verNode[v];
vSize = v;
}

~graph(){
int i;
for (i = 0; i <= vSize - 1; i++){
edgeNode* tmp = table[i].head;
while (tmp != NULL){
table[i].head = table[i].head->next;
delete tmp;
tmp = table[i].head;
}
}
delete[] table;
}

void insert(int u, int w){
table[u].head = new edgeNode(w, table[u].head);
table[w].head = new edgeNode(u, table[w].head);
//cout << "Insert " << u << ", " << w << " successfully." << endl;
}

// Return the farthest node away from u
int bfs(int u){
char *flag = new char[vSize + 10];
memset(flag, 0, sizeof(char) * (vSize + 10));

int *queue = new int[vSize + 10];
int front, end;
front = end = 0;
queue[end++] = u;
flag[u] = 1;
table[u].step = 0;
int cur;
//int last;

while (end > front){
cur = queue[front++];
//cout << "dequeue: " << cur << endl;
edgeNode* tmp = table[cur].head;
while (tmp){
if (!flag[tmp->end]){
queue[end++] = tmp->end;
table[tmp->end].step = table[cur].step + 1;
flag[tmp->end] = 1;
}
tmp = tmp->next;
}
}

delete[] flag;
delete[] queue;
return cur; // The last node to dequeue
}

inline int step(int u){
return table[u].step;
}
};

int main(){
int N, i, A, B;
scanf("%d", &N);
graph gp(N);

for (i = 1; i <= N - 1; i++){
scanf("%d%d", &A, &B);
gp.insert(A - 1, B - 1);
}

int cur = gp.bfs(0);
int last = gp.bfs(cur);
cout << gp.step(last) << endl;

return 0;
}

        这题当然也可以用DFS来做,有空再补上
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据结构 bfs