例题8-10:抄书(二分答案+贪心)

例题8-10:抄书
这里写图片描述
由于要求有多解时s(1)尽量小,s(1)一样时s(2)尽量小,采用贪心从后往前找

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<string>
#include<cmath>
#include<set>
#include<queue>
#include<map>
#include<stack>
#include<vector>
#include<list>
#include<deque>
using namespace std;
typedef long long ll;
const int maxn = 1e6 + 10;
const double eps = 1e-6;
const int INF = 1 << 30;
const int dir[4][2] = {1,0,0,1,0,-1,-1,0};
int T, n, k;
ll a[550], sum, mm;
bool judge(ll x)
{
    ll tot = 0, ans = 1;
    for(int i = 0; i < n; i++)
    {
        if(tot + a[i] <= x)tot+=a[i];
        else tot = a[i],ans++;
        if(ans > k)return false;
    }
    return true;
}
void input()
{
    sum = 0, mm = 0;
    cin >> n >> k;
    for(int i = 0; i < n; i++)
    {
        scanf("%lld", &a[i]);
        mm = max(mm, a[i]);
        sum += a[i];
    }
}
void out(ll x)
{
    //cout<<x<<endl;
    ll tot = 0, ans = 1;
    bool v[550];
    memset(v, 0, sizeof(v));
    for(int i = n - 1; i >= 0; i--)///贪心
    {
        if(tot + a[i] <= x)tot+=a[i];
        else{
            tot = a[i];
            v[i] = 1;
            ans++;
        }
    }
    for(int i = 0; i < n && ans < k; i++)
    {
        if(!v[i])v[i] = 1, ans++;
    }
    for(int i = 0; i < n - 1; i++)
    {
        cout << a[i] << " " ;
        if(v[i])cout<<"/ ";
    }
    cout<<a[n - 1]<<endl;
}
void solve(ll x, ll y)
{
    ll m;
    while(x < y)
    {
        m = (y + x) / 2;
        if(judge(m))y = m;
        else x = m + 1;
    }
    sum = 0;
    ///这里的答案是x!!!
    out(x);///输出很复杂;
}
int main()
{
    scanf("%d",&T);
    while(T--)
    {
        input();
        solve(mm, sum);
    }
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值