牛客竞赛语法入门班数组栈、队列和stl习题 装进肚子

B-装进肚子

最开始想用深搜,把所有的方案都试一遍,最后再排个序。

这个方法递归的层数太多,导致段错误,只过了样例。事实证明,递归慎用,容易堆栈溢出。代码如下:

#include<iostream>
#include<cstring>
using namespace std ;
const int N = 1e5 ;
int n , k , c = 0 , ans= 0 ;
int a[N+5] , b[N+5] , visa[N+5] , visb[N+5];
void dfs(int j){
    if(j == n){
        if(ans > c) c = ans ;
        return ;
    }
    j += k ;
    if(!visa[j]){
        visa[j] = 1 ;
        ans += a[j] ;
        dfs(j) ;
        ans -= a[j] ;
        visa[j] = 0 ;
        j -= k ;
    }
    if(!visb[j]){
        visb[j] = 1 ;
        ans += b[j] ;
        dfs(j) ;
        ans -= b[j] ;
        visb[j] = 0 ;
        j -= k ;    
    }
}
int main (){
    memset(visa , 0 , sizeof visa) ;
    memset(visb , 0 , sizeof visb) ;
    cin >> n >> k ;
    for(int i = 1 ; i <= n ; i++){
        cin >> a[i]; 
    }
    for(int i = 1 ; i <= n ; i++){
        cin >> b[i] ;
    }
    dfs(0) ;
    cout << c << endl ;
    return 0  ;
}

这个方法还存在题意理解错误的问题,直接跳过了(nk ,  nk+k)的糖。

后来,网上搜了下题解,看了别人的代码,明明白白的 。一颗糖最后总要被吃的,早上或者晚上。为了使甜蜜值最大,只需要比较这颗糖在早上吃甜蜜值高还是晚上甜蜜值高。因此要用结构体进行排序。在题目要求下,早上只能吃k颗糖,将排序后的结构体里早上的前k项和晚上的后n-k项累加得出结果。代码如下:

 #include<iostream>
#include<algorithm>
using namespace std ;
const int N = 1e5 ;
int n , k , ans = 0 ;
struct node{
    int x ,  y ;
};
node a[N+5] ;
bool cmp(node a , node b){
    return a.x-a.y > b.x-b.y ;
}
int main (){
    cin >> n >> k ;
    for(int i = 0 ; i < n ; i++){
        scanf("%d" , &a[i].x) ;
    }
    for(int i = 0 ; i < n ; i++){
        scanf("%d" , &a[i].y) ;
    }
    sort(a , a+n , cmp) ;
    for(int j = 0 ; j < k ; j++){
        ans += a[j].x ;
    }
    for(int j = k ; j < n ; j++){
        ans += a[j].y ;
    }
    cout << ans << endl ;
    return 0 ;
}

最后,感谢一下Ok-ok博主的代码,原文在这:

牛客每日练习----比赛,完全平方数,装进肚子
 https://blog.csdn.net/weixin_44170305/article/details/105729542

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值