流水依依

希望朋友们有个好的身体,开开心心工作与学习。

博客园 首页 新随笔 联系 订阅 管理

1350: To Add Which?

Time Limit: 1 Sec  Memory Limit: 128 MB

Description

    There is an integer sequence with N integers. You can use 1 unit of cost to increase any integer in the sequence by 1.
    Could you tell us the least units of cost to achieve that, the absolute value of difference between any two adjacent integers is not more than D?

Input

    The first line has one integer T, means there are T test cases.
    For each test case, the first line has two integers ND (1 <= N <= 105, 0 <= D < 109), which have the same meaning as above. The next line has N integers describing the sequence. Every integer in this sequence is in range [0, 109).
    The size of the input file will not exceed 5MB.

Output

    For each test case, print an integer in one line, indicates the desired answer.

Sample Input

3
5 2
1 3 5 3 5
5 1
1 2 3 5 6
5 2
1 7 3 5 9

Sample Output

0
3
8

HINT

 

Source

中南大学第一届长沙地区程序设计邀请赛

    贪心的思想,大数不会变大,变化的是小数。

    每次取出最大的数,扩展左右2个点。

#include <iostream>
#include <string>
#include <string.h>
#include <map>
#include <stdio.h>
#include <algorithm>
#include <queue>
#include <vector>
#include <math.h>
#include <set>
#define Max(a,b) ((a)>(b)?(a):(b))
#define Min(a,b) ((a)<(b)?(a):(b))
using namespace std ;
typedef long long LL ;
const int Max_N = 100008 ;
int N ,D ;
int num[Max_N] ;
LL sum ;

struct Node{
     int  id ;
     int  num ;
     Node(){} ;
     Node(int i ,int n):id(i),num(n){} ;
     friend bool operator < (const Node A ,const Node B){
          return A.num < B.num ;
     }
};

int gan(int id , int x){
     if(id> N || id < 1)
        return  0 ;
     if(fabs(num[id] - x) <= D)
        return  0 ;
     sum += (LL)(x - D - num[id]) ;
     num[id] = x - D ;
     return  x - D ;
}

LL gao(){
    sum = 0 ;
    scanf("%d%d",&N,&D) ;
    int n_num ;
    priority_queue<Node> que ;
    for(int i = 1 ; i <= N ; i++){
        scanf("%d",&num[i]) ;
        que.push(Node(i,num[i])) ;
    }
    while(!que.empty()){
        Node now = que.top() ;
        que.pop() ;
        if(now.num != num[now.id])
          continue ;
        n_num = gan(now.id -1 ,now.num) ;
        if(n_num)
           que.push(Node(now.id - 1,n_num)) ;
        n_num = gan(now.id +1 ,now.num) ;
        if(n_num)
           que.push(Node(now.id + 1,n_num)) ;
    }
    return sum ;
}

int main(){
    int T ;
    scanf("%d",&T) ;
    while(T--){
          cout<<gao()<<endl ;
    }
    return 0 ;
}

 

posted on 2013-12-12 22:03  流水依依  阅读(293)  评论(0编辑  收藏  举报