HDU 5191 Building Blocks (類比),hdu5191
Building Blocks
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 829 Accepted Submission(s): 186
Problem DescriptionAfter enjoying the movie,LeLe went home alone. LeLe decided to build blocks.
LeLe has already built n piles. He wants to move some blocks to make W consecutive piles with exactly the same height H.
LeLe already put all of his blocks in these piles, which means he can not add any blocks into them. Besides, he can move a block from one pile to another or a new one,but not the position betweens two piles already exists.For instance,after one move,"3 2 3" can become "2 2 4" or "3 2 2 1",but not "3 1 1 3".
You are request to calculate the minimum blocks should LeLe move. InputThere are multiple test cases, about100 cases.
The first line of input contains three integers n,W,H(1≤n,W,H≤50000).n indicate n piles blocks.
For the next line ,there are n integers A1,A2,A3,……,An indicate the height of each piles. (1≤Ai≤50000)
The height of a block is 1. OutputOutput the minimum number of blocks should LeLe move.
If there is no solution, output "-1" (without quotes).
Sample Input
4 3 21 2 3 54 4 41 2 3 4
Sample Output
1-1HintIn first case, LeLe move one block from third pile to first pile.
SourceBestCoder Round #34
題目連結:http://acm.hdu.edu.cn/showproblem.php?pid=5191
題目大意:n堆木塊,每個木塊高為1,第i堆高ai,現在要求組成連續w個高度為h的木堆,最少移動幾個木塊,注意不能添加木塊,且移動時,不可移動置兩已存在的堆之間
題目分析:枚舉區間w的位置,因為要考慮ai的最小值都大於h的情況,因此我們需要將區間分成三段[1 - w], [w+1, w+n], [w+n, w+w+n],動態維護區間w,用t1,t2表示當前區間內需要加入的和需要移出的木塊數,區間每移動一次,頭尾兩個值要修改,下面給出範例1動態維護的過程:
0 0 0 1 2 3 5 0 0 0
t1 6 6 6 5 3 1 0 2 4 6
t2 0 0 0 0 0 1 4 4 3 0
交的時候用C++交
#include <cstdio>#include <cstring>#include <algorithm>#define ll long longusing namespace std;int const MAX = 150005;ll a[MAX];int main(){ ll n, w, h; while(scanf("%I64d %I64d %I64d", &n, &w, &h) != EOF) { ll sum = 0; memset(a, 0, sizeof(a)); for(int i = w + 1; i <= w + n; i++) { scanf("%I64d", &a[i]); sum += a[i]; } if(sum < h * w) { printf("-1\n"); continue; } ll t1 = w * h, ans = w * h, t2 = 0; for(int i = w + 1; i <= w + w + n; i++) { if(a[i - w] < h) t1 -= (h - a[i - w]); else t2 -= (a[i - w] - h); if(a[i] < h) t1 += (h - a[i]); else t2 += (a[i] - h); ans = min(ans, max(t1, t2)); } printf("%I64d\n", ans); }}