【例题 8-10 UVA

【链接】 我是链接,点我呀:)
【题意】

在这里输入题意

【题解】

二分最后的最大值的最小值。 得到ans 然后从后往前尽量划分。 如果发现不够分成k个。 那么就从第一个开始接着分restk个(每隔1个分1块 中间遇到之前分了的就直接跳过

【代码】

/*
  	1.Shoud it use long long ?
  	2.Have you ever test several sample(at least therr) yourself?
  	3.Can you promise that the solution is right? At least,the main ideal
  	4.use the puts("") or putchar() or printf and such things?
  	5.init the used array or any value?
  	6.use error MAX_VALUE?
  	7.use scanf instead of cin/cout?
  	8.whatch out the detail input require
*/
/*
    一定在这里写完思路再敲代码!!!
    二分最后的最大值的最小值。
    得到ans
    然后从后往前尽量划分。
    如果发现不够分成k个。
    那么就从第一个开始接着分restk个(每隔1个分1块
    中间遇到之前分了的就直接跳过
*/
#include <bits/stdc++.h>
#define ll long long
using namespace std;

const int N = 500;

int n,k,a[N+10];
bool tag[N+10];

bool ok(ll up){
    ll now = 0;
    int times = 1;
    for (int i = 1;i <= n;i++)
        if (a[i]>up) return false;
            else
                {
                    now+=a[i];
                    if (now > up){
                        now = a[i];
                        times++;
                    }
                }
    return times<=k;
}

int main(){
	#ifdef LOCAL_DEFINE
	    freopen("rush_in.txt", "r", stdin);
	#endif
	ios::sync_with_stdio(0),cin.tie(0);
    int T;
    cin >> T;
    while (T--){
        memset(tag,0,sizeof tag);
        cin >> n >> k;
        for (int i = 1;i <= n;i++) cin >> a[i];
        ll l = 0,r = 50e8,temp = -1;
        while (l <= r){
            ll mid = (l+r)>>1;
            if (ok(mid)){
                temp = mid;
                r = mid-1;
            }else l = mid + 1;
        }
        k--;
        ll now = a[n];
        for (int i = n-1;k>0 && i >= 1;i--){
            now += a[i];
            if (now > temp){
                k--;
                now = a[i];
                tag[i] = 1;
            }
        }
        if (k > 0){
            for (int i = 1;k>0 && i <= n;i++)
                if (!tag[i]){
                    tag[i] = 1;
                    k--;
                }
        }
        for (int i = 1;i <= n;i++)
        {
            cout << a[i];
            if (tag[i]) cout <<" /";
            if (i!=n) cout << ' ';else cout << endl;
        }
    }
	return 0;
}

原文地址:https://www.cnblogs.com/AWCXV/p/8185301.html