Cod sursa(job #2914960)

Utilizator cristia_razvanCristia Razvan cristia_razvan Data 21 iulie 2022 14:28:44
Problema Salvare Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.53 kb

#include <bits/stdc++.h>
using namespace std;

#define pb push_back
#define dbg(x) cout << #x <<": " << x << "\n";
#define sz(x) ((int)x.size())

using ll = long long;

const string fn = "salvare";
ifstream fin(fn + ".in");
ofstream fout(fn + ".out");

int n, k;
int cnt, nd;
int dist[1005];
bool v[1005];

vector<int> g[1005];

int sol;
vector<int> ans;
vector<int> aux;


void dfs(int nod, int dad) {

	int mn = 2e9;
	for (auto i : g[nod]) {
		if (i != dad) {
			dfs(i, nod);
			dist[nod]  = max(dist[nod], dist[i] + 1);
			mn = min(mn, dist[i] + 1);
		}
	}
	if (dist[nod] == nd) {
		++cnt; dist[nod] = - nd - 1;
		aux.pb(nod);
	}
	else if (- mn - 1 >= dist[nod]) {
		dist[nod] = mn;
	}

}

bool ok(int D) {

	nd = D; cnt = 0;
	for (int i = 1; i <= n ; ++i)
		dist[i] = 0;
	aux.clear();
	dfs(1, 0);
	if (dist[1] >= 0)
		++cnt, aux.pb(1);
	return (cnt <= k);


}


int main() {

	ios_base::sync_with_stdio(false);
	cin.tie();

	fin >> n >> k;
	for (int i = 1; i < n; ++i) {
		int x, y;
		fin >> x >> y;
		g[x].pb(y);
		g[y].pb(x);
	}

	int st, dr, mid;
	st = 0; dr = n;
	while (st <= dr) {

		mid = (st + dr) >> 1;
		if (ok(mid)) {
			sol = mid;
			ans.clear();
			for (auto i : aux)
				ans.pb(i);
			dr = mid - 1;
		}
		else st = mid + 1;

	}

	sort(ans.begin(), ans.end());
	k -= sz(ans);

	fout << sol << '\n';


	for (auto i : ans)
		fout << i << " ", v[i] = 1;

	for (int i = 1; i <= n; ++i)
		if (!v[i] && k)
			fout << i << " ", k--;


	return 0;
}