Barn Repair

本文介绍了一个名为Barn1的问题,并使用C++实现了解决方案。通过对相邻两个元素间差值的统计和排序,采取贪心策略确定最优解。适用于算法竞赛中的区间覆盖问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

链接

分析:我们不断统计相邻两个元素之间的差值,按照差值从大到小排序,在进行贪心即可

 1 /*
 2     PROB:barn1
 3     ID:wanghan
 4     LANG:C++
 5 */
 6 #include "iostream"
 7 #include "cstdio"
 8 #include "cstring"
 9 #include "string"
10 #include "cmath"
11 #include "algorithm"
12 using namespace std;
13 const int maxn=220;
14 int m,s,c;
15 int stall[maxn];
16 struct  Node
17 {    
18     int sub,id;    
19 };
20 Node p[maxn];
21 bool cmp(Node x,Node y){
22     return x.sub>y.sub;
23 }
24 int vis[maxn];
25 int main()
26 {
27     freopen("barn1.in", "r", stdin);  
28     freopen("barn1.out", "w", stdout);
29     cin>>m>>s>>c;
30     for(int i=0;i<c;i++){
31         cin>>stall[i];
32     }
33     sort(stall,stall+c);
34     for(int i=1;i<c;i++){
35         p[i].id=i;
36         p[i].sub=stall[i]-stall[i-1];
37     }
38     //p[c].id=c;
39     //p[c].sub=s-stall[c-1];
40     sort(p+1,p+c,cmp);
41     if(m>=c){
42         cout<<c<<endl;
43     }else{
44         int cnt=stall[c-1]-stall[0];
45         //cout<<cnt<<endl;
46         for(int i=1;i<m;i++){
47             cnt-=p[i].sub;
48             //cout<<"sub:"<<p[i].sub<<endl;
49             //cout<<cnt<<endl;
50         }
51         cout<<cnt+m<<endl;
52     }
53 }
View Code

 

转载于:https://www.cnblogs.com/wolf940509/p/6980402.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值