Pagini recente » Cod sursa (job #1511565) | Cod sursa (job #360247) | Cod sursa (job #3230626) | Cod sursa (job #1190345) | Cod sursa (job #1586294)
#include <cstdio>
#include <vector>
#include <utility>
#include <queue>
#include <algorithm>
using namespace std;
template<class Type>
class Heap {
public:
Heap() {
size = 0;
heap.push_back(make_pair(0,0));
}
Type Top() const {
return heap[1].second;
}
void Insert(const Type &object,const int &objectVal) {
heap.push_back(make_pair(objectVal, object));
++size;
Percolate(size);
}
void Pop() {
Swap(size, 1);
heap.pop_back();
--size;
Sift(1);
}
private:
int size;
vector<pair<int, Type>> heap;
void Swap(const int x, const int y) {
swap(heap[x], heap[y]);
}
void Percolate(const int x) {
int father = x / 2;
if (father > 0 && heap[x] < heap[father]) {
Swap(x, father);
Percolate(father);
}
}
void Sift(const int x) {
int son = 2 * x;
if (son + 1 <= size && heap[son + 1] < heap[son])
++son;
if (son <= size && heap[son] < heap[x]) {
Swap(x, son);
Sift(son);
}
}
};
Heap<short> heap;
short N,K,a,b,Elim;
vector<short> G[10001];
int h[10001];
short d[10001];
inline short Parent(short& x) {
return G[x][0];
}
inline void del(short x,short y) {
for (int i = 0; i < G[x].size(); i++)
if (G[x][i] == y) {
G[x].erase(G[x].begin()+i);
return;
}
}
int main()
{
freopen("cezar.in", "r", stdin);
freopen("cezar.out", "w", stdout);
scanf("%hd%hd",&N,&K);
for (int i = 1; i < N; i++) {
scanf("%hd%hd",&a,&b);
G[a].push_back(b);
G[b].push_back(a);
}
for (int i = 1; i <= N; i++)
if (G[i].size() == 1) {
heap.Insert(i,0);
}
Elim = 0;
while (Elim != N - K - 1) {
++Elim;
a = heap.Top(); heap.Pop();
b = Parent(a);
del(b,a);
d[b] = d[b] + 1 + d[a];
h[b] = h[b] + h[a] + d[a] + 1;
h[a] = 0;
if (G[b].size() == 1) {
heap.Insert(b,h[b]);
}
}
int Ans = 0;
for (int i = 1; i <= N; i++) {
Ans += h[i];
//printf("%d ",h[i]);
}
printf("%d",Ans);
}