1. 程式人生 > >codeforces 348B B. Apple Tree(dfs+數論)

codeforces 348B B. Apple Tree(dfs+數論)

題目連結:

題目大意:

給出一棵樹和每個葉子節點的權值,每個點的值是它子樹裡的葉子節點的權值的總和,讓每個節點的孩子的值都相等,只能通過縮減每個葉子的權值,問最少縮減的值是多少。

題目分析:

  • 我們定義mul[MAX]陣列代表某個葉子合法情況下應該佔到整棵樹權值的1mul[u]
  • 我們進行一遍dfs,處理除葉子節點的mul的最小公倍數,這樣能夠保證滿足所有的點合法的最小的數。
  • 然後用x記錄整棵樹最大的合法總權值(所有合法總權值mul[u]*a[u]裡最小的)
  • 然後找到能夠整除Lcm且離x最近的值,就是x-x%lcm
  • 然後就能夠得到最後結果,但是求的是要削去的部分的權值

AC程式碼:

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <vector>
#define MAX 100007

using namespace std;

typedef long long LL;
const LL INF=(1LL<<60);
LL sum,a[MAX],mul[MAX],x,lcm,ans;
int n,u,v;
vector<int> e[MAX];

LL gcd ( LL a , LL b )
{
    return
!b?a:gcd(b,a%b); } void add ( int u , int v ) { e[u].push_back ( v ); e[v].push_back ( u ); } void dfs ( int u , int p ) { if ( ans == -1 ) return; if ( p == -1 ) mul[u] = 1; if ( e[u].size() == 1 && p != -1 ) { //cout << mul[u] << " " << a[u] << endl;
x = min ( x , mul[u]*a[u] ); lcm = lcm*mul[u]/gcd(mul[u],lcm); if ( lcm > x ) { ans = -1; return; } } LL num = 0; for ( int i = 0 ; i < e[u].size() ; i++ ) { int v = e[u][i]; if ( v == p ) continue; num++; } for ( int i = 0; i < e[u].size() ; i++ ) { int v = e[u][i]; if ( v == p ) continue; mul[v] = mul[u]*num; dfs ( v , u ); } } int main ( ) { while ( ~scanf ( "%d" , &n ) ) { sum = 0; ans = 0; lcm = 1; x = INF; for ( int i = 0 ; i < MAX ; i++ ) e[i].clear(); for ( int i = 1 ; i <= n ; i++ ) { scanf ( "%lld" , &a[i] ); sum += a[i]; } for ( int i = 1 ; i < n ; i++ ) { scanf ( "%d%d" , &u , &v ); add ( u , v ); } dfs ( 1 , -1 ); if ( ans == -1 ) printf ( "%lld\n" , sum ); else printf ( "%lld\n" , sum - x + x%lcm ); } }