hihocoder 1050



        题意为求一棵树中的最长路径。这里采用两次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来做,有空再补上


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值