您的位置:首页 > 其它

Codeforces Round #426 (Div. 2) D. The Bakery (线段树)

2017-08-01 10:47 447 查看
D. The Bakery

time limit per test
2.5 seconds

memory limit per test
256 megabytes

input
standard input

output
standard output

1 #include <iostream>
2 #include <cstdio>
3 #include <cstring>
4 #include <algorithm>
5 #include <bits/stdc++.h>
6 using namespace std;
7 const int maxn=350005;
8 int dp[55][maxn];
9 int tree[maxn<<2],lazy[maxn];
10 int pos[maxn],pre[maxn];
11 int n,k;
12 void push_down(int t)
13 {
14     if(tree[t])
15     {
16         tree[t<<1|1]+=lazy[t];
17         tree[t<<1]+=lazy[t];
18         lazy[t<<1|1]+=lazy[t];
19         lazy[t<<1]+=lazy[t];
20         lazy[t]=0;
21     }
22 }
23 void push_up(int t)
24 {
25     tree[t]=max(tree[t<<1],tree[t<<1|1]);
26 }
27 void build(int k,int l,int r,int t)
28 {
29     lazy[t]=0;
30     if(l==r)
31     {
32         tree[t]=dp[k][l-1];
33
34         return ;
35     }
36     int mid=(l+r)/2;
37     build(k,l,mid,t<<1);
38     build(k,mid+1,r,t<<1|1);
39     push_up(t);
40 }
41
42 void update(int L,int R,int l,int r,int t)
43 {
44     if(L<=l&&r<=R)
45     {
46         tree[t]++;
47         lazy[t]++;
48         return ;
49     }
50     int mid=(l+r)/2;
51     push_down(t);
52     if(L>=mid) update(L,R,l,mid,t<<1);
53     if(R<mid) update(L,R,mid+1,r,t<<1|1);
54     push_up(t);
55 }
56 int query(int L,int R,int l,int r,int t)
57 {
58     if(L<=l&&r<=R)
59     {
60         return tree[t];
61     }
62     int mid=(l+r)/2;
63     push_down(t);
64     int ans=0;
65     if(L<=mid) ans=max(ans,query(L,R,l,mid,t<<1));
66     if(R>mid) ans=max(ans,query(L,R,mid+1,r,t<<1|1));
67     push_up(t);
68     return ans;
69 }
70 int main()
71 {
72     while(~scanf("%d%d",&n,&k))
73     {
74         memset(pre,0,sizeof(pre));
75         memset(pos,0,sizeof(pos));
76         memset(tree,0,sizeof(tree));
77         memset(lazy,0,sizeof(lazy));
78         int x;
79         for(int i=1;i<=n;i++)
80         {
81             scanf("%d",&x);
82             pre[i]=pos[x]+1;
83             pos[x]=i;
84         }
85         for(int i=1;i<=k;i++)
86         {
87             build(i-1,1,n,1);
88             for(int j=1;j<=n;j++)
89             {
90                 update(pre[j],j,1,n,1);
91                 dp[i][j]=query(1,j,1,n,1);
92             }
93         }
94         printf("%d\n",dp[k]
);
95     }
96     return 0;
97 }


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: