LuoguP1351 联合权值 (枚举)

题目链接
枚举每个点,遍历和他相邻的点,然后答案一边更新就可以了.
最大值的时候一定是两个最大值相乘,一边遍历一边记录就好了.
时间复杂度.\(O(n)\)

#include <iostream>
#include <cstdio>
#define max(a,b) a > b ? a : b
const int maxN = 200000 + 7;
const int mod = 10007;

int w[maxN];

inline int read() {
    int x = 0,f = 1;char c = getchar();
    while(c < '0' || c > '9') {if(c == '-')f = -1;c = getchar();}
    while(c >= '0' && c <= '9') {x = x * 10 + c - '0';c = getchar();}
    return x * f;
}

struct Node {
    int v,nex;
}Map[maxN << 1];
int num,head[maxN];

void add_Node(int u,int v) {
    Map[++ num] = {v,head[u]};
    head[u] = num;
    return ;
}

int ans_max,ans;

int main() {
    int n = read(),u,v;
    for(int i = 1;i < n;++ i) {
        u = read();v = read();
        add_Node(u,v);add_Node(v,u);
    }
    for(int i = 1;i <= n;++ i) 
        w[i] = read() % mod;
    for(int i = 1;i <= n;++ i) {
        int tmp_sum = 0,tmp_max = 0;
        for(int j = head[i];j;j = Map[j].nex) {
            int v = Map[j].v;
            ans_max = max(ans_max,tmp_max * w[v]);
            tmp_max = max(tmp_max,w[v]);
        }
        for(int j = head[i];j;j = Map[j].nex) {
            int v = Map[j].v;
            tmp_sum += w[v];
            tmp_sum %= mod; 
        }
        for(int j = head[i];j;j = Map[j].nex) {
            int v = Map[j].v;
            ans = (ans + (tmp_sum - w[v]) * w[v] ) % mod;
        }
    }
    printf("%d %d", ans_max,(ans + mod) % mod);
    return 0;
}
posted @ 2018-09-25 21:03  Rlif  阅读(125)  评论(0编辑  收藏  举报