【题解】Luogu P1269 信号放大器 贪心

基本算法2-1

 


 

贪心选择放置放大器的点

dep[i]dep[i]表示ii子树内离他最远的距离,dis[i]dis[i]表示ii到他父亲的距离

只有当dep[i]+dis[i]>才需要一个放大器,然后把这个点的dep[i]清零

这样贪心一定最优

code

复制代码
 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 namespace gengyf{
 4 #define ll long long
 5 const int maxn=1e5+10;
 6 const int mod=1e9;
 7 inline int read(){
 8     int f=1,x=0;char s=getchar();
 9     while(s<'0'||s>'9'){if(s=='-')f=-1;s=getchar();}
10     while(s>='0'&&s<='9'){x=x*10+s-'0';s=getchar();}
11     return f*x;
12 }
13 int n,p,fl,ans;
14 struct edge{
15     int nxt,to,w;
16 }e[maxn*2];
17 int head[maxn],cnt,dis[maxn],dep[maxn];
18 inline void add(int from,int to,int w){
19     e[++cnt].to=to;e[cnt].w=w;e[cnt].nxt=head[from];head[from]=cnt;
20 }
21 void dfs(int x,int fa){
22     for(int i=head[x];i;i=e[i].nxt){
23         if(e[i].to!=fa){
24             dis[e[i].to]=e[i].w;
25             dfs(e[i].to,x);
26             dep[x]=max(dep[e[i].to]+e[i].w,dep[x]);
27         }
28     }
29     if(dis[x]+dep[x]>p){
30         ans++;dep[x]=0;
31     }
32 }
33 int main(){
34     n=read();
35     for(int i=1;i<=n;i++){
36         int k;k=read();
37         for(int j=1;j<=k;j++){
38             int v,w;
39             v=read();w=read();add(i,v,w);
40             fl=max(fl,w);
41         }
42     }
43     p=read();
44     if(fl>=p){
45         cout<<"No solution."<<endl;
46         return 0;
47     }
48     dfs(1,1);
49     printf("%d",ans);
50     return 0;
51 }
52 }
53 signed main(){
54   gengyf::main();
55   return 0;
56 }
View Code
复制代码

 

posted @   喵の耳  阅读(291)  评论(0编辑  收藏  举报
编辑推荐:
· 用 C# 插值字符串处理器写一个 sscanf
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
· .NET Core内存结构体系(Windows环境)底层原理浅谈
· C# 深度学习:对抗生成网络(GAN)训练头像生成模型
阅读排行:
· 手把手教你更优雅的享受 DeepSeek
· AI工具推荐:领先的开源 AI 代码助手——Continue
· 探秘Transformer系列之(2)---总体架构
· V-Control:一个基于 .NET MAUI 的开箱即用的UI组件库
· 乌龟冬眠箱湿度监控系统和AI辅助建议功能的实现
点击右上角即可分享
微信分享提示