F - To Add Which?

本文介绍了一种针对整数序列的调整算法,旨在通过增加序列中任意整数的值来最小化相邻整数间的绝对差不超过给定阈值所需的最小成本。文章提供了具体的输入输出示例及一个使用C语言实现的示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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\n",sum);
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值