码迷,mamicode.com
首页 > 其他好文 > 详细

【Code Chef】April Challenge 2019

时间:2019-04-15 19:44:58      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:div   void   play   ...   com   codechef   ++   show   close   

Subtree Removal

很显然不可能选择砍掉一对有祖先关系的子树。令$f_i$表示$i$子树的答案,如果$i$不被砍,那就是$a_i + \sum\limits_j f_j$;如果$i$被砍,那就是$-x$。取个$max$就好了。

时间复杂度$O(n)$。

技术图片
#include <bits/stdc++.h>

using namespace std;

const int N = 1e5 + 5;

int tc, n, xx;
int a[N];
vector<int> g[N];
long long f[N];

void Dfs(int x, int ft) {
  f[x] = a[x];
  for (int i = 0; i < g[x].size(); ++i) {
    int v = g[x][i];
    if (v == ft) continue;
    Dfs(v, x);
    f[x] += f[v];
  }
  f[x] = max(f[x], -(long long)xx);
}

int main() {
  scanf("%d", &tc);
  for (; tc--; ) {
    scanf("%d%d", &n, &xx);
    for (int i = 1; i <= n; ++i) {
      scanf("%d", &a[i]);
    }
    for (int i = 1, x, y; i < n; ++i) {
      scanf("%d%d", &x, &y);
      g[x].push_back(y);
      g[y].push_back(x);
    }

    Dfs(1, 0);
    printf("%lld\n", f[1]);
    
    // remember to clear up
    for (int i = 1; i <= n; ++i) {
      g[i].clear();
    }
  }
  
  return 0;
}
View Code

 

Playing with Numbers

在模$m$意义下,$a * k(k \in \mathbb{N})$能表示的最大的数就是$m - (a, m)$。容易推导出一个叶子的答案就是$m_i - (m, a_{b_1}, a_{b_2}, ... , a_{b_w})$,其中$b$表示$i$号点的祖先链。

时间复杂度$O(nlogn)$。

技术图片
#include <bits/stdc++.h>

using namespace std;

const int N = 1e5 + 5;

int tc, n;
vector<int> g[N];
long long a[N], m[N], gcd[N];

void Dfs(int x, int ft) {
  for (int i = 0; i < g[x].size(); ++i) {
    int v = g[x][i];
    if (v == ft) continue;
    gcd[v] = __gcd(gcd[x], a[v]);
    Dfs(v, x);
  }
}

int main() {
  scanf("%d", &tc);
  for (; tc--; ) {
    scanf("%d", &n);
    for (int i = 1, x, y; i < n; ++i) {
      scanf("%d%d", &x, &y);
      g[x].push_back(y);
      g[y].push_back(x);
    }
    for (int i = 1; i <= n; ++i) {
      scanf("%lld", &a[i]);
    }
    for (int i = 1; i <= n; ++i) {
      scanf("%lld", &m[i]);
    }
    gcd[1] = a[1];
    Dfs(1, 0);

    for (int i = 2; i <= n; ++i) {
      if (g[i].size() == 1) {
        long long d = __gcd(gcd[i], m[i]);
        printf("%lld ", m[i] - d);
      }
    }
    printf("\n");
    
    // remember to clear up
    for (int i = 1; i <= n; ++i) {
      g[i].clear();
    }
  }
  
  return 0;
}
View Code

 

【Code Chef】April Challenge 2019

标签:div   void   play   ...   com   codechef   ++   show   close   

原文地址:https://www.cnblogs.com/Dance-Of-Faith/p/10712425.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!