标签:div scanf strong 复杂度 memset show ios def new
题意:给定一个无根树,每个点有一个权值。若两个点 \(i,j\) 之间距离为\(2\),则有联合权值 \(w_i \times w_j\)。求所有的联合权值的和与最大值
分析:
实现:
注意事项:
代码:
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
using namespace std;
#define int long long
const int MAXN = 200200;
const int MOD = 10007;
int n, w[MAXN], cnt, Max = 0, ans, sumw[MAXN], vis1[MAXN], vis2[MAXN], first[MAXN], second[MAXN];
struct edge
{
int v; edge *next;
}pool[MAXN << 1], *head[MAXN];
inline void addedge(int u, int v)
{
edge *p = &pool[++cnt], *q = &pool[++cnt];
p->v = v, p->next = head[u]; head[u] = p;
q->v = u, q->next = head[v]; head[v] = q;
}
void dfs1(int u)
{
vis1[u] = 1;
for(edge *p = head[u]; p; p = p->next)
{
sumw[u] += w[p->v];
if(first[u] < w[p->v]) second[u] = first[u], first[u] = w[p->v];
else second[u] = max(second[u], w[p->v]);
if(!vis1[p->v]) dfs1(p->v);
}
}
void dfs2(int u)
{
vis2[u] = 1;
Max = max(Max, first[u] * second[u]);
for(edge *p = head[u]; p; p = p->next)
{
int lh = sumw[u] * w[p->v] - w[p->v] * w[p->v];
ans = (ans + lh) % MOD;
if(!vis2[p->v]) dfs2(p->v);
}
}
#undef int
int main()
{
memset(second, -1, sizeof(second));
scanf("%d", &n);
for(int i = 1; i < n; i++)
{
int u, v;
scanf("%d%d", &u, &v);
addedge(u, v);
}
for(int i = 1; i <= n; i++) scanf("%lld", &w[i]);
dfs1(1);
dfs2(1);
printf("%lld %lld", Max, ans);
return 0;
}
题解【luogup1351 NOIp提高组2014 联合权值】
标签:div scanf strong 复杂度 memset show ios def new
原文地址:https://www.cnblogs.com/TLE666/p/8909145.html