1. 程式人生 > >Gym - 101438F Tree Game

Gym - 101438F Tree Game

force com codeforce 題解 mod urn etc div class

題面在這裏

題解見註釋 (強行優化成 O(N))

/*
    ans = (V[x] - E[xx]) - (V[y] - E[yy])
        = (n mod 2) + E[yy] - E[xx]
        = (n mod 2) + (E[yy] + 1/2 * E[xy]) - (E[xx] + 1/2 * E[xy])
        = (n mod 2) + 1/2 sum_of_degree_in_y - 1/2 sum_of_degree_in_x
*/

#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int N=200005;

inline int read(){
    int x=0; char ch=getchar();
    for(;!isdigit(ch);ch=getchar());
    for(;isdigit(ch);ch=getchar()) x=x*10+ch-‘0‘;
    return x;
}

int n,d[N],ans,a[N];

int main(){
	n=read();
	for(int i=1;i<n;i++) d[read()]++,d[read()]++;
	for(int i=1;i<=n;i++) a[d[i]]++;
	for(int i=1,now=1;i<=n;i++) if(a[i]&1) ans+=(now&1)?-i:i,now^=1;
	ans=(ans>>1)+(n&1),printf("%d\n",ans);
	return 0;
}

Gym - 101438F Tree Game