小 Q 的棋盘

来源:互联网 发布:电脑软件论坛排行榜 编辑:程序博客网 时间:2024/04/29 02:11

链接:

  http://exam.upc.edu.cn/problem.php?id=3779


题目:

题目描述
小Q正在设计一种棋类游戏。在小Q设计的游戏中,棋子可以放在棋盘上的格点中。某些格点之间有连线,棋子只能在有连线的格点之间移动。整个棋盘上共有V个格点,编号为0,1,2…,V-1,它们是连通的,也就是说棋子从任意格点出发,总能到达所有的格点。小Q在设计棋盘时,还保证棋子从一个格点移动到另外任一格点的路径是唯一的。
小Q现在想知道,当棋子从格点0出发,移动N步最多能经过多少格点。格点可以重复经过多次,但不重复计数。

输入
第一行包含2个正整数V,N,其中V表示格点总数,N表示移动步数。
接下来V-1行,每行两个数Ai,Bi,表示编号为Ai,Bi的两个格点之间有连线。
V,N ≤ 100 , 0 ≤ Ai , Bi < V

输出
输出一行一个整数,表示最多经过的格点数量。

样例输入

5 2
1 0
2 1
3 2
4 3

样例输出

3

提示
从格点 0 出发移动 2 步。经过0, 1, 2这 3 个格点。


思路:

  如果走往返的话,每个点的花费是2,如果只走一遍的话,每个点的花费就是1。

  所以尽量把步数留给最深的那个,直接DFS找最长子链。


实现:

#include <iostream>#include <algorithm>#include <set>#include <string>#include <vector>#include <queue>#include <map>#include <stack>#include <functional>#include <iomanip>#include <cstdio>#include <cstring>#include <cmath>#include <climits>#include <cctype>using namespace std;vector<int> edge[110];int v, n, dep[110], maxn;inline void dfs(const int u, const int pre) {    if (dep[u] <= n) {        maxn = max(maxn, dep[u] + n + 2 >> 1);        for (register int i = 0, v; i < edge[u].size(); i++)            if ((v = edge[u][i]) != pre) {                dep[v] = dep[u] + 1;                dfs(v, u);            }    }}int main() {#ifndef ONLINE_JUDGE    freopen("in.txt", "r", stdin);#endif    ios_base::sync_with_stdio(false);cin.tie(0);    cin >> v >> n;    for (register int i = 1,a,b; i < v; i++) {        cin >> a >> b;        edge[a].push_back(b);        edge[b].push_back(a);    }    dfs(0, 0);    cout << (maxn < v ? maxn : v) << '\n';    return 0;}
原创粉丝点击