codeforces 1288E. Messenger Simulator(树状数组)

链接:https://codeforces.com/contest/1288/problem/E

题意:序列p的长度为n,初始序列为1 2 3 4 ...n,然后有m次操作,每次指定序列中一个数移动到第一位,然后剩下的所有序列往后移动一位,求每个数在出现过的所有历史序列中所在位置索引的最大值和最小值。

思路:用一个树状数组维护序列的位置,在序列的前面空出m个位置,目的是留给m次操作移动数字到前m个位置。初始时,在输入数据的时候,用pos数组记录所有数字的位置为 i+m,然后树状数组的 i+m处更新+1代表第i+m个位置放了一个数,每次移动操作时,在该位置做-1的更新操作表示此处清零,该位置已经没有放置数字,然后可以用树状数组查询该位置前面部分的区间和,就表示前面有多少个数,自然而然就可以更新这个数出现位置的最大值了,而最小值更新则为:如果进行了移动操作,那么该数字位置的最小值就是1了,因为把该数字放在了序列最前面,最后再遍历一遍所有数字,查询更新一些没有进行移动操作的数出现位置的最大值。具体看代码

AC代码:

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<algorithm>
 5 #include<vector>
 6 #include<queue> 
 7 using namespace std;
 8 typedef long long ll;
 9 const int maxn = 3e5+5;
10 int t[maxn*2];
11 int ansMin[maxn+1],ansMax[maxn+1];
12 int n,m;
13 inline int lowbit(int x){
14     return x&(-x);
15 }
16 void add(int x,int k){
17     while(x<=n+m){
18         t[x] = t[x] + k;
19         x +=lowbit(x);
20     }
21 }
22 int get(int x){
23     int ans = 0;
24     while(x>=1){
25         ans+=t[x];
26         x-=lowbit(x);
27     }
28     return ans;
29 }
30 int main(){
31     scanf("%d%d",&n,&m);
32     int pos[n+m+1];
33     for(int i = 1;i<=n;i++){
34         pos[i] = i + m;//初始化元素的位置,pos[i]为元素i的位置
35         ansMin[i] = i,ansMax[i] = i;
36         add(i + m,1);//树状数组该位置更新+1
37     }
38     for(int i = 0;i<m;i++){
39         int temp;
40         scanf("%d",&temp);
41         ansMin[temp] = 1;
42         add(pos[temp],-1);//该位置-1,
43         add(m-i,1);//移动到最前面,树状数组+1
44         ansMax[temp] = max(ansMax[temp],get(pos[temp]));//查询前面有多少个元素,做max的更新
45         pos[temp] = m - i;//更新位置
46     }
47     for(int i = 1;i<=n;i++){
48         ansMax[i] = max(ansMax[i],get(pos[i]));//最后check没有进行移动操作的元素
49     }
50     for(int i = 1;i<=n;i++){
51         printf("%d %d\n",ansMin[i],ansMax[i]);
52     }
53     return 0;
54 }

猜你喜欢

转载自www.cnblogs.com/AaronChang/p/12210874.html