跳到正文

个人记录

Enjoy 15 函数 lipshitz

zzr8178541919约 4 分钟
原文
文章信息与版本

文章信息

发布
2020年12月3日
收录
2025年12月12日
更新
2026年9月19日
篇幅
约 4 分钟

版本

  1. v1当前

题目描述

大 M 为了正在学习函数的光滑性并对Lipschitz 常数非常感兴趣:当一个定义域为 [l,r] 的函数 f,对于定义域内的任意 x,y 都有 |f(x)−f(y)|≤K×|x−y| 时,则称 K 的最小值为该函数在 [l,r] 上的 Lipschitz 常数。

然而大 M 并不满足于函数,所以他定义:对于一个序列 v[1]…v[n],当 1≤x<y≤n 且 x,y 均为整数时,同样满足 |v[x]−v[y]|≤K×|x−y| ,则称 K 的最小整数值为序列 v 的 Lipschitz 常数。

现在给你一个长度为 n 的序列v[1]…v[n] 并给出 q 个询问,对于每对询问[l,r],你需要求出 v[l]…v[r] 的所有子序列 v[x]…v[y](l≤x<y≤r)的 LipschitzLipschitz 常数之和。

这可难不倒会编程的你。

输入格式

第一行两个整数 n 和 q,分别表示序列的长度以及询问的个数。

第二行 n 个数,表示 v[1]…v[n];

接下来 q 行,每行两个数 l和 r,表示询问的区间为 [l,r];

输出格式

对于每个询问,输出一行一个数,即 v[l]…v[r] 的所有子序列的 Lipschitz 常数之和。

数据范围及提示

对于 30% 的数据,n≤500;

对于 60% 的数据,n≤5×104 10^4;

对于 100% 的数据,n≤10510^5 ,q≤100,0≤v[i]≤10810^8 。

Solution:

单调栈好题!

先做一遍绝对值的差分,得到数组bib_i

然后会发现一个性质:

对于一个序列,要求K,只需要看其中相邻的两个数即可。

因为你把公式移一下项,发现它长得很像平均数。

对于 a,ba,b 有max⁡(a,b)>a+b2\max(a,b)> \dfrac{a+b}{2} ,更多的可以用数学归纳法证明

那肯定一个一个选更好

接下来用贡献法!

就变成了单调栈的问题。

codecode

C++
#include<cmath>
#include<cstring>
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<queue>
#define int long long
#define reg register
using namespace std;
const int maxn=5e5+5;
inline int read()
{
	int x=0,f=1;
	char ch=getchar();
	while(ch<'0' || ch>'9')
	{
		if(ch=='-')
		f=-1;
		ch=getchar();
	}
	while(ch>='0' && ch<='9')
	{
		x=x*10+ch-'0';
		ch=getchar();
	}
	return x*f;
}
int n;
int a[maxn];
int Q;
int v[maxn];
int q[maxn];
int head1=1;
int tail=0;
int l[maxn];
int r[maxn];
signed main()
{
	n=read(),Q=read();
	for(int i=1;i<=n;i++)
	{
		a[i]=read();
	}
	while(Q--)
	{
		int l1=read(),r1=read();
		int tot=0;
		for(int i=l1;i<=r1-1;i++)
		{
			v[++tot]=abs(a[i+1]-a[i]);
		}
		head1=1,tail=0;
		for(int i=1;i<=tot;i++)
		{
			while(head1<=tail && v[i]>v[q[tail]])
			{
				r[q[tail]]=i;	
				tail--;
			}			
			q[++tail]=i;
		}
		while(head1<=tail)
		{
			r[q[tail]]=tot+1;
			tail--;
		}
		head1=1,tail=0;
		for(int i=tot;i>=1;i--)
		{
			while(head1<=tail && v[i]>=v[q[tail]])
			{
				l[q[tail]]=i;	
				tail--;
			}			
			q[++tail]=i;
		}
		while(head1<=tail)
		{
			l[q[tail]]=0;
			tail--;
		}
		int ans=0;
		for(int i=1;i<=tot;i++)
		{
			int nowl=l[i]+1;
			int nowr=r[i]-1;
			ans=ans+v[i]*(i-nowl+1)*(nowr-i+1);
		}
		printf("%lld\n",ans);
	}
	return 0;
}
原文