牛客小白月赛6 C 桃花

链接:https://www.nowcoder.com/acm/contest/136/C
来源:牛客网
 

桃花一簇开无主,可爱深红映浅红。

                                        ——《题百叶桃花》

    桃花长在桃树上,树的每个节点有一个桃花,调皮的HtBest想摘尽可能多的桃花。HtBest有一个魔法棒,摘到树上任意一条链上的所有桃花,由于HtBest法力有限,只能使用一次魔法棒,请求出Htbest最多可以摘到多少个桃花。

输入描述:

第一行有一个正整数n,表示桃树的节点个数。
接下来n-1行,第i行两个正整数ai,bi ,表示桃树上的节点ai,bi之间有一条边。

输出描述:

第一行一个整数,表示HtBest使用一次魔法棒最多可以摘到多少桃花。

示例1

输入

复制

3
1 2
2 3

输出

复制

3

示例2

输入

复制

3
1 2
1 3

输出

复制

3

示例3

输入

复制

4
1 2
2 3
3 4

输出

复制

4

 

给你一个图,求最长的一条链的节点的数量.

#include <iostream>
#include <cstdio>
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 10;
const int inf = 0x3f3f3f3f;
struct node
{
	int u, v, w, next;
}edge[maxn << 2];
int n, m, tot, _max;
int head[maxn], f[maxn], dist[maxn], path[maxn];
bool vis[maxn];
void init(int n)
{
	int N = n;
	for (int i = 0; i <= N; i++)
	{
		head[i] = -1;
	}
	memset(vis, false, sizeof(vis));
	_max = -1;
	tot = 0;
}
void addedge(int u, int v, int w)
{
	edge[tot].u = u;
	edge[tot].v = v;
	edge[tot].w = w;
	edge[tot].next = head[u];
	head[u] = tot++;

	edge[tot].u = v;
	edge[tot].v = u;
	edge[tot].w = w;
	edge[tot].next = head[v];
	head[v] = tot++;
	return;
}
int dfs(int x)
{
	int t1, t2;
	t1 = t2 = 0;
	vis[x] = true;
	if (head[x] == -1)
	{
		return 1;
	}
	for (int i = head[x]; i != -1; i = edge[i].next)
	{
		if (vis[edge[i].v])
		{
			continue;
		}
		t1 = max(t1, dfs(edge[i].v));
		if (t1 > t2)
		{
			swap(t1, t2);
		}
	}
	_max = max(t1 + t2 + 1, _max);
	return t2 + 1;
}
int main(int argc, const char * argv[])
{
	freopen("C://input.txt", "r", stdin);
	scanf("%d", &n);
	init(n);
	for (int i = 1; i < n; i++)
	{
		int u, v;
		scanf("%d%d", &u, &v);
		addedge(u, v, 1);
	}
	dfs(1);
	printf("%d\n", _max);
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值