zoukankan      html  css  js  c++  java
  • F

    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 N, D (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

    数据比较水,n^2也能过,有nlogn的算法,要用线段树和递归,暂时不会写。。。

    #include<stdio.h>
    #include<math.h>
    long long a[100005];
    int main()
    {
    	int T,i,j;
    	long long n,m,sum;
    	scanf("%d",&T);
    	while(T--)
    	{
    		scanf("%lld%lld",&n,&m);
    		sum=0;
    		for(i=1;i<=n;i++)
    		{
    			scanf("%lld",&a[i]);
    		}
    		for(i=2;i<=n;i++)
    		{
               if(fabs(a[i]-a[i-1])<=m )
    		   continue;
    		   else if(a[i]<a[i-1])
    		   {
       			  sum=sum+a[i-1]-m-a[i];
       			  a[i]=a[i-1]-m;
    	       }
    	       else if(a[i]>a[i-1])
    	       {
           		  sum=sum+a[i]-m-a[i-1];
           		  a[i-1]=a[i]-m;
           		  for(j=i-1;j>=2;j--)
           		  {
      		       	 if(fabs(a[j]-a[j-1])<=m )
      		       	 break;
      		       	 if(a[j]>a[j-1])
      		       	 {
     	       		   sum=sum+a[j]-m-a[j-1];
    	   	           a[j-1]=a[j]-m;
       		         }
    	           }
       	        }
             }
    		printf("%lld
    ",sum);
    	}
    }

  • 相关阅读:
    九大经典算法之插入排序、希尔排序
    1072 开学寄语 (20 分)
    1070 结绳 (25 分
    查找字符串中的所有数字
    通过类继承计算梯形面积
    将命令的输出生成一个Web页面
    从Internet下载一个文件
    使用Excel管理命令输出
    将一个命令的输出保存到CSV文件
    使用属性存储用户编号和姓名
  • 原文地址:https://www.cnblogs.com/herumw/p/9464866.html
Copyright © 2011-2022 走看看