zoukankan      html  css  js  c++  java
  • 【NOIP2014】 联合权值

    【题目链接】

               点击打开链接

    【算法】

             如果(u,v)的距离为2,那么有两种可能 :

             1.u和v为祖孙关系

             2.u和v为兄弟关系

             树形DP即可,详见代码

    【代码】

             

    #include<bits/stdc++.h>
    using namespace std;
    #define MAXN 200000
    #define MOD 10007
    
    int i,u,v,N,ans1,ans2;
    int w[MAXN+10],max1[MAXN+10],max2[MAXN+10],fa[MAXN+10],sum[MAXN+10];
    vector<int> E[MAXN+10];
    
    template <typename T> inline void read(T &x) {
            int f=1; x=0;
            char c = getchar();
            for (; !isdigit(c); c = getchar()) { if (c == '-') f = -f; }
            for (; isdigit(c); c = getchar()) x = x * 10 + c - '0';
            x *= f;
    }
    
    template <typename T> inline void write(T x) {
        if (x < 0) { putchar('-'); x = -x; }
        if (x > 9) write(x/10);
        putchar(x%10+'0');
    }
    
    template <typename T> inline void writeln(T x) {
        write(x);
        puts("");
    }
    
    inline void dfs(int root) {
            int i,son,cnt=0;
            for (i = 0; i < E[root].size(); i++) {
                    son = E[root][i];
                    if (son != fa[root]) {
                            fa[son] = root;
                            dfs(son);
                            cnt = (cnt + w[son] * w[son]) % MOD;
                            ans1 = max(ans1,w[root]*max1[son]);
                            ans2 = (ans2 + (w[root] * sum[son] * 2) % MOD) % MOD;
                            sum[root] = (sum[root] + w[son]) % MOD;
                            if (w[son] > max1[root]) {
                                    max2[root] = max1[root];
                                    max1[root] = w[son];
                            } else if (w[son] > max2[root])
                                    max2[root] = w[son];
                    }
            }        
            ans1 = max(ans1,max1[root]*max2[root]);
            ans2 = (ans2 + (sum[root] * sum[root] % MOD - cnt + MOD) % MOD) % MOD;
    }
    
    int main() {
        
            read(N);
            for (i = 1; i < N; i++) {
                    read(u); read(v);
                    E[u].push_back(v);
                    E[v].push_back(u);    
            }
            for (i = 1; i <= N; i++) read(w[i]);
            dfs(1);
            
            write(ans1); putchar(' '); write(ans2); puts("");
            
            return 0;
        
    }
  • 相关阅读:
    手写token解析器、语法解析器、LLVM IR生成器(GO语言)
    Windows下切分文件(GnuWin32)
    转载:教你分分钟搞定Docker私有仓库Registry
    marathon传参一
    DC/OS安装
    自己写编程语言-m语言
    揽货最短路径解决方案算法
    揽货最短路径解决方案算法
    用keras作CNN卷积网络书本分类(书本、非书本)
    用keras做SQL注入攻击的判断
  • 原文地址:https://www.cnblogs.com/evenbao/p/9196417.html
Copyright © 2011-2022 走看看