Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <algorithm>
- #include <vector>
- #include <stdlib.h>
- using namespace std;
- using ll = long long;
- using ull = unsigned long long;
- int maxi_depth = 0;
- int saved = -1;
- int dfs(vector<vector<int>> &graph, vector<int> &visited, vector<int> &dfs_answer, int v, int depth = 0) {
- depth++;
- if (depth > maxi_depth) {
- maxi_depth = depth;
- saved = v;
- }
- if (dfs_answer[v] != 0) return dfs_answer[v];
- visited[v] = true;
- int count = 0;
- int result = 0;
- for (int i = 0; i < graph[v].size(); i++) {
- if (!visited[graph[v][i]]) {
- count++;
- result = max(result, dfs(graph, visited, dfs_answer, graph[v][i], depth));
- }
- }
- if (count == 0) { //значит это лист
- dfs_answer[v] = 1;
- return 1;
- }
- else {
- return result + 1;
- dfs_answer[v] = result + 1;
- }
- }
- int main() {
- ios_base::sync_with_stdio(false);
- cin.tie(nullptr);
- int N, M;
- cin >> N >> M; //N вершин и M километров
- vector<vector<int>> graph(N);
- vector<int> visited(N, 0);
- vector<int> dfs_answer(N, 0);
- for (int i = 0; i < N - 1; i++) {
- int beg, end;
- cin >> beg >> end;
- graph[beg - 1].push_back(end - 1);
- graph[end - 1].push_back(beg - 1);
- }
- int result = dfs(graph, visited, dfs_answer, graph[0][0]) + 1;
- visited.clear();
- dfs_answer.clear();
- vector<int> visited2(N, 0);
- vector<int> dfs_answer2(N, 0);
- result = dfs(graph, visited2, dfs_answer2, saved - 1) + 1;
- if (M < result) cout << M + 1;
- else {
- M = M - result;
- result += M / 2;
- cout << result;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement