旅行者征程

 

 我的代码:

#include<iostream>
#include <set>
using namespace std;
#define MAX 1000000

struct Node
{
	int v;
	struct Node* next=NULL;
};
struct Tree
{
	int u;
	struct Node* firstNode = NULL;
}t[MAX + 1]; //下标范围从0到1000000
int mark[MAX + 1] = { 0 };
set<int> sb;
void add(int x, int y)
{
	Node* tmp = new Node;
	if (t[x].firstNode == NULL)
	{
		tmp->v = y;
		t[x].firstNode = tmp;
	}
	else
	{
		Node* line = t[x].firstNode;
		while (line->next != NULL)line = line->next;
		tmp->v = y;
		line->next = tmp;
	}
}

class solution
{
public:
	void dfs(int head, int x,int& maxdot,int &maxi,int lenth,int mark[])
	{
		Node* tmp = t[x].firstNode;
		mark[x] = 1;
		if (head != x)lenth++;//刚访问时不用加长度
		while (tmp != NULL)
		{
			if (mark[tmp->v] == 0)
			{
				dfs(head, tmp->v, maxdot, maxi, lenth, mark);
			}
			tmp = tmp->next;
		}
		if (lenth > maxi)
		{
			sb.clear();
			maxi = lenth;
			maxdot = x;
			sb.insert(x);
		}
		else if (lenth == maxi)
		{
			maxdot = x;
			sb.insert(x);
		}
		return;
	}
};

void Dot(int n,int head, int x,int &maxdot,int &maxi)
{
	solution s;
	for (int i = 0; i < n+1; i++)mark[i] = 0;
	s.dfs(head, x, maxdot, maxi, 0, mark);
}

int main()
{
	int n;
	cin >> n;
	int x, y;
	for (int i = 0; i < n - 1; i++)
	{
		cin >> x >> y;
		add(x, y);
		add(y, x);
	}

	set<int>rec;
	int p1, p2, m1, m2;
	p1 = -1;
	m1 = -1;
	p2 = -1;
	m2 = -1;
	Dot(n,1, 1,p1,m1);
	for (auto it = sb.begin(); it != sb.end(); it++)rec.insert(*it);
	Dot(n,p1, p1, p2, m2);
	for (auto it = sb.begin(); it != sb.end(); it++)rec.insert(*it);

	for (auto it = rec.begin(); it != rec.end(); it++)cout << *it << ' ';
	

	return 0;
}

通过两次dfs找出直径并记录下可以走出直径的点,但这样超时了,应该用动态规划,还没研究出来呵

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值