可并堆试水--BZOJ1367: [Baltic2004]sequence

n<=1e6个数，把他们修改成递增序列需把每个数增加或减少的总量最小是多少？

{b1,b2,……,bn,bn+1,……,bm}，那么一定有bn<=u，否则把前半部分改成{u,u,……,u}不会更差。同理bn+1>=v。

 1 #include<string.h>
2 #include<stdlib.h>
3 #include<stdio.h>
4 #include<math.h>
5 //#include<assert.h>
6 #include<algorithm>
7 //#include<iostream>
8 using namespace std;
9
10 int n;
11 #define maxn 1000011
12 int root[maxn];
13 int find(int x) {return x==root[x]?x:(root[x]=find(root[x]));}
14 struct leftist
15 {
16     struct Node
17     {
18         int v,ls,rs,dis,size;
19     }a[maxn];
20     int size;
21     leftist() {a[0].dis=-1;}
22     int merge(int x,int y)
23     {
24         if (!x || !y) return x^y;
25         if (a[x].v<a[y].v) {int t=x; x=y; y=t;}
26         a[x].rs=merge(a[x].rs,y);
27         if (a[a[x].ls].dis<a[a[x].rs].dis) {int t=a[x].ls; a[x].ls=a[x].rs; a[x].rs=t;}
28         a[x].dis=a[a[x].rs].dis+1;
29         a[x].size=a[a[x].ls].size+a[a[x].rs].size+1;
30         return x;
31     }
32     void push(int x,int &root,int val)
33     {
34         a[x].v=val; a[x].ls=a[x].rs=a[x].dis=0; a[x].size=1;
35         root=merge(root,x);
36     }
37     int top(int root) {return a[root].v;}
38     void pop(int &root) {root=merge(a[root].ls,a[root].rs);}
39 }q;
40
41 int a[maxn],sta[maxn],die[maxn],top;
42 int main()
43 {
44     scanf("%d",&n);
45     for (int i=1;i<=n;i++) scanf("%d",&a[i]),a[i]-=i;
46     for (int i=1;i<=n;i++)
47     {
48         q.push(i,root[i],a[i]); int x,y;
49         while (top && q.top(x=find(root[sta[top]]))>q.top(y=find(root[i])))
50         {
51             bool flag=0;
52             if (((sta[top]-sta[top-1])&1) && ((i-sta[top])&1)) flag=1;
53             root[x]=root[y]=q.merge(x,y); x=root[x];
54             if (flag) die[x]=1,q.pop(root[x]),root[root[x]]=root[x];
55             top--;
56         }
57         sta[++top]=i;
58     }
59     #define LL long long
60     LL ans=0;
61     for (int i=1;i<=n;i++) ans+=fabs(a[i]-q.top(find(root[i])));
62     printf("%lld\n",ans);
63     return 0;
64 }
View Code

posted @ 2018-01-11 08:24  Blue233333  阅读(123)  评论(0编辑  收藏  举报