CF1375G. Tree Modification
Solution
假设我们取定了根,那么只可能从深度大的点接到深度小的点,我们每次取一个高度为2的子树接到该子树的父亲,这样取一定不劣,操作次数相当于是偶数深度点(根深度为0)的个数减一。
注意到所有奇数深度的点为根的答案都相同,偶数同理。
因此整合之后,相当于是奇数深度和偶数深度点的个数的较小值减一。
时间复杂度 O ( n ) O(n) O(n)。
Code
#include <bits/stdc++.h>
using namespace std;
template<typename T> inline bool upmin(T &x, T y) { return y < x ? x = y, 1 : 0; }
template<typename T> inline bool upmax(T &x, T y) { return x < y ? x = y, 1 : 0; }
#define MP(A,B) make_pair(A,B)
#define PB(A) push_back(A)
#define SIZE(A) ((int)A.size())
#define LEN(A) ((int)A.length())
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define fi first
#define se second
typedef long long ll;
typedef unsigned long long ull;
typedef long double lod;
typedef pair<int, int> PR;
typedef vector<int> VI;
const lod eps = 1e-9;
const lod pi = acos(-1);
const int oo = 1 << 30;
const ll loo = 1ll << 60;
const int mods = 1e9 + 7;
const int inv2 = (mods + 1) >> 1;
const int MAXN = 500005;
const int INF = 0x3f3f3f3f; //1061109567
/*--------------------------------------------------------------------*/
namespace FastIO{
constexpr int SIZE = (1 << 21) + 1;
int num = 0, f;
char ibuf[SIZE], obuf[SIZE], que[65], *iS, *iT, *oS = obuf, *oT = obuf + SIZE - 1, c;
#define gc() (iS == iT ? (iT = ((iS = ibuf) + fread(ibuf, 1, SIZE, stdin)), (iS == iT ? EOF : *iS ++)) : *iS ++)
inline void flush() {
fwrite(obuf, 1, oS - obuf, stdout);
oS = obuf;
}
inline void putc(char c) {
*oS ++ = c;
if (oS == oT) flush();
}
inline void getc(char &c) {
for (c = gc(); c != '<' && c != '>' && c != EOF; c = gc());
}
inline void reads(char *st) {
char c;
int n = 0;
getc(st[++ n]);
for (c = gc(); c == '<' || c == '>' ; c = gc()) st[++ n] = c;
st[n + 1] = '\0';
}
template<class I>
inline void read(I &x) {
for (f = 1, c = gc(); c < '0' || c > '9' ; c = gc()) if (c == '-') f = -1;
for (x = 0; c >= '0' && c <= '9' ; c = gc()) x = (x << 3) + (x << 1) + (c & 15);
x *= f;
}
template<class I>
inline void print(I x) {
if (x < 0) putc('-'), x = -x;
if (!x) putc('0');
while (x) que[++ num] = x % 10 + 48, x /= 10;
while (num) putc(que[num --]);
}
struct Flusher_{~Flusher_(){flush();}} io_Flusher_;
}
using FastIO :: read;
using FastIO :: putc;
using FastIO :: reads;
using FastIO :: print;
vector<int> e[MAXN];
int dep[MAXN], num[2];
void dfs(int x, int father) {
dep[x] = dep[father] + 1;
++ num[dep[x] & 1];
for (auto v : e[x]) {
if (v == father) continue;
dfs(v, x);
}
}
signed main() {
#ifndef ONLINE_JUDGE
freopen("a.in", "r", stdin);
#endif
int n;
read(n);
for (int i = 1, u, v; i < n ; ++ i) read(u), read(v), e[u].PB(v), e[v].PB(u);
dfs(1, 0);
print(min(num[0], num[1]) - 1);
return 0;
}