程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> POJ 3273 Monthly Expense 二分答案

POJ 3273 Monthly Expense 二分答案

編輯:C++入門知識

Monthly Expense Time Limit: 2000MS Memory Limit: 65536K Total Submissions: 13281 Accepted: 5362

Description

Farmer John is an astounding accounting wizard and has realized he might run out of money to run the farm. He has already calculated and recorded the exact amount of money (1 ≤ moneyi ≤ 10,000) that he will need to spend each day over the next N (1 ≤ N ≤ 100,000) days.

FJ wants to create a budget for a sequential set of exactly M (1 ≤ MN) fiscal periods called "fajomonths". Each of these fajomonths contains a set of 1 or more consecutive days. Every day is contained in exactly one fajomonth.

FJ's goal is to arrange the fajomonths so as to minimize the expenses of the fajomonth with the highest spending and thus determine his monthly spending limit.

Input

Line 1: Two space-separated integers: N and M
Lines 2..N+1: Line i+1 contains the number of dollars Farmer John spends on the ith day

Output

Line 1: The smallest possible monthly limit Farmer John can afford to live with.

Sample Input

7 5
100
400
300
100
500
101
400

Sample Output

500

Hint

If Farmer John schedules the months so that the first two days are a month, the third and fourth are a month, and the last three are their own months, he spends at most $500 in any month. Any other method of scheduling gives a larger minimum monthly limit.

題解

又是一個二分題。題目的意思是說,在接下來的n天裡,Farmer John每天需要花money[i]錢,把這些天分成k份(每份都是連續的天),要求每份的和盡量少,輸出這個最小的和。

依舊是二分答案二分答案。。。但是特別奇怪,如果用一個res維護當前可行值就會WA,而且R也得用r = mid 而不是r = mid - 1。。。

這個二分真是難

代碼示例

/****
	*@author    Shen
	*@title     poj 3273
	*/

#include 
#include 
#include 
#include 
using namespace std;

int n, k;
int r, v[100005];
int maxa = 0, mina = 0;

bool test(int x)
{
    int sum = 0, cnt = 1;
    for (int i = 0; i < n; i++)
    {
        if (sum + v[i] <= x)
            sum += v[i];
        else
            cnt++, sum = v[i];
    }
    //printf("\t%s with x = %d, result is that sum = %d.\n", __func__, x, sum);
    return cnt <= k;
}

int Bsearch(int l, int r)
{
    while (l < r)
    {
        int mid = (r + l) / 2;
        //printf("l = %d, r = %d, mid = %d.\n", l, r, mid);
        if (test(mid))
            r = mid;
        else
            l = mid + 1;
    }
    return l;
}

void solve()
{
    maxa = mina = 0;
    for (int i = 0; i < n; i++)
    {
        scanf("%d", &v[i]);
        maxa += v[i];
        mina = max(mina, v[i]);
    }
    int ans = Bsearch(mina, maxa);
    printf("%d\n", ans);
}

int main()
{
    while (~scanf("%d%d", &n, &k))
        solve();
    return 0;
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved