HDU 5933 ArcSoft's Office Rearrangement(贪心)

来源:互联网 发布:毕向东java视频百度云 编辑:程序博客网 时间:2024/05/16 16:13

Problem Description
ArcSoft, Inc. is a leading global professional computer photography and computer vision technology company.

There are N working blocks in ArcSoft company, which form a straight line. The CEO of ArcSoft thinks that every block should have equal number of employees, so he wants to re-arrange the current blocks into K new blocks by the following two operations:

  • merge two neighbor blocks into a new block, and the new block’s size is the sum of two old blocks’.
  • split one block into two new blocks, and you can assign the size of each block, but the sum should be equal to the old block.

Now the CEO wants to know the minimum operations to re-arrange current blocks into K block with equal size, please help him.

Input
First line contains an integer T, which indicates the number of test cases.

Every test case begins with one line which two integers N and K, which is the number of old blocks and new blocks.

The second line contains N numbers a1, a2, ⋯, aN, indicating the size of current blocks.

Limits
1≤T≤100
1≤N≤105
1≤K≤105
1≤ai≤105

Output
For every test case, you should output ‘Case #x: y’, where x indicates the case number and counts from 1 and y is the minimum operations.

If the CEO can’t re-arrange K new blocks with equal size, y equals -1.

Sample Input
3
1 3
14
3 1
2 3 4
3 6
1 2 3

Sample Output
Case #1: -1
Case #2: 2
Case #3: 3

Source
2016年中国大学生程序设计竞赛(杭州)

题意:给你n个工作间的长度,问你能不能通过以下两个操作,使其分成k个相等长度的空间。如果能输出最小操作次数,不能输出-1;
操作1:合并两个相邻的工作空间。
操作2:使一个工作空间分成任意两个长度的空间。

思路:
先求出sum,如果sum % k == 0,能够确定是有解的,且每个空间长度为ave = sum/k,然枚举一遍,用一个变量s,不断的合并空间,累加到s上,如果s是ave的倍数,就s拆分,操作次数加上s/ave - 1,最后即可求出结果。
代码如下:

#include<bits/stdc++.h>using namespace std;const int MAX = 100010;typedef long long ll;int n,k,a[MAX];ll sum,ave;ll solve(){    ll res = 0,s = 0;    if(sum %k != 0) return -1;    ave = sum/k;    for(int i=1;i<=n;++i){        s += a[i];        if(s % ave == 0){            res += s/ave - 1;            s = 0;        }        else{            res++;        }    }    return res;}int main(void){    int T;    scanf("%d",&T);    int Case = 0;    while(T--){        sum = 0;        scanf("%d %d",&n,&k);        for(int i=1;i<=n;++i){            scanf("%d",&a[i]);            sum += a[i];        }        printf("Case #%d: %lld\n",++Case,solve());    }    return 0;}