首页 技术 正文
技术 2022年11月17日
0 收藏 577 点赞 4,843 浏览 1440 个字

[Luogu 1351] NOIP2014 联合权值

<题目链接>


存图,对于每一个点 \(u\),遍历它的所有邻接点。以 \(u\) 为中转点的点对中,\((x,y)\) 的联合权值 \(w_x \cdot w_y\) 最大,当且仅当 \(x\) 与 \(y\) 的点权在 \(u\) 的所有邻接点中是前两大的。

成功尝试内嵌 HTML 控制背景色,开心。

每遍历一个点 \(v\),它对联合权值之和 \(\mathrm{sum}\) 的贡献,等于其点权 \(w_v\) 乘目前已遍历点的点权和 \(\mathrm{NodeSum}\) 再乘 \(2\),即 \(\mathrm{sum} += 2w_v \cdot \mathrm{NodeSum}\)。(取模省略,代码中体现)

然后一边求 \(u\) 的邻接点中的最大点权 \(\mathrm{max1}\) 和次大点权 \(\mathrm{max2}\),一边更新 \(\mathrm{NodeSum}\)(教练跟我说更新这个的过程叫什么前序和优化)。

\(u\) 的邻接点遍历完毕后,\(\mathrm{sum}\) 也更新完毕了。至于最大联合权值 \(\mathrm{ans}\),比较当前 \(\mathrm{ans}\) 与此次遍历求出的 \(\mathrm{max1} \cdot \mathrm{max2}\),更新最大值即可。

最终输出 \(\mathrm{ans}\) 与 \(\mathrm{sum}\) 即可。

#include <algorithm>
#include <cstdio>
using std::max;
const int MAXN=2000010,P=10007;
int n,ans,sum,w[MAXN];
struct Edge
{
int to;
Edge *next;
Edge(int to,Edge* next):to(to),next(next){}
~Edge(void)
{
if(next!=nullptr)
delete next;
}
}*head[MAXN];
void Initialize(void)
{
for(int i=1;i<=n;++i)
head[i]=nullptr;
}
void AddEdges(int u,int v)
{
head[u]=new Edge(v,head[u]);
head[v]=new Edge(u,head[v]);
}
void Solve(int u)
{
int NodeSum=0,max1=0,max2=0;
for(Edge *i=head[u];i!=nullptr;i=i->next)
{
int v=i->to;
sum=(sum+(NodeSum*w[v]<<1))%P;
if(max1<w[v])
{
max2=max1;
max1=w[v];
}
else
max2=max(max2,w[v]);
NodeSum=(NodeSum+w[v])%P;
}
ans=max(ans,max1*max2);
}
void Destroy(void)
{
for(int i=1;i<=n;++i)
delete head[i];
}
int main(int argc,char** argv)
{
scanf("%d",&n);
for(int i=1,u,v;i<n;++i)
{
scanf("%d %d",&u,&v);
AddEdges(u,v);
}
for(int i=1;i<=n;++i)
scanf("%d",&w[i]);
for(int i=1;i<=n;++i)
Solve(i);
printf("%d %d\n",ans,sum);
return 0;
}

谢谢阅读。

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,110
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,584
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,431
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,202
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,837
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,920