BZOJ 1367

1367: [Baltic2004]sequence

Time Limit: 20 Sec  Memory Limit: 64 MB
Submit: 1111  Solved: 439

[Submit][Status][Discuss]

Description

Input

Output

一个整数R

Sample Input

7
9
4
8
20
14
15
18

Sample Output

13

HINT

所求的Z序列为6,7,8,13,14,15,18.
R=13

这是一道权限题。

学长论文:左偏树的特点及其应用

cnt是区间标号,tot是左偏树的节点标号

另外,如果读入的时候不进行a[i]-=i,算出来的数列不一定会是单调增的,有可能相邻的项会相同。

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#define N 1000005
#define ll long long
using namespace std;
struct leftist
{
    int l,r,fa,d,size;
ll v; }h[N]; ll ans,a[N];
int n,w[N],root[N],l[N],r[N],tot=0,cnt=0; int merge(int x,int y) { if(x*y==0)return x+y; if(h[x].v<h[y].v)swap(x,y); h[x].r=merge(h[x].r,y); h[h[x].r].fa=x; h[x].size=h[h[x].l].size+h[h[x].r].size+1; if(h[h[x].l].d<h[h[x].r].d)swap(h[x].l,h[x].r); h[x].d=h[h[x].r].d+1; return x; } int pop(int &x) { x=merge(h[x].l,h[x].r); } int newnode(int x) { h[++tot].v=x; h[tot].l=h[tot].r=h[tot].fa=h[tot].d=0; h[tot].size=1; return tot; } int main() { scanf("%d",&n); for(int i=1;i<=n;i++){scanf("%lld",&a[i]);a[i]-=i;} for(int i=1;i<=n;i++) { cnt++; root[cnt]=newnode(a[i]); l[cnt]=r[cnt]=i; while(cnt>1 && h[root[cnt]].v<h[root[cnt-1]].v) { cnt--; root[cnt]=merge(root[cnt],root[cnt+1]); r[cnt]=r[cnt+1]; while(h[root[cnt]].size*2>r[cnt]-l[cnt]+2)pop(root[cnt]); } } long long ans=0; for(int i=1;i<=cnt;i++) { ll t=h[root[i]].v; //printf("%d %d %d ",t,l[i],r[i]); for(int j=l[i];j<=r[i];j++) ans+=abs(t-a[j]); } printf("%lld",ans); //system("pause"); return 0; }

应该过了吧。。。我没有权限号。。目测没有什么问题2333

要注意int和long long之间的加减法很容易出现奇怪的问题,导致几组奇怪的数据过不了。

原文地址:https://www.cnblogs.com/fdfzhyf/p/8151972.html