4 條題解
-
0
莫队题解:
第一眼:区间处理问题。
第二眼:没有强制在线。
第三眼:不带修改
第四眼:数据
综上所述:莫队显然是较好的比赛选择(好写不易错) 莫队的思想不再赘述,想必大家都已经了解
回到题目,可以发现不仅查询数 ,而且数组中的任意元素都 ,于是在莫队的加减操作中,可以通过桶排序来实现均摊 处理(证明请见下文)
同时,本题推荐使用奇偶排序进行常数优化,本人优化后的代码以最高 通过最大测试点。不保证没有优化或者常数过大的代码通过本题
以下为本人代码:
#include<bits/stdc++.h> using namespace std; #define debug(x); cerr<<__LINE__<<" : "<<#x<<" "<<x<<"\n"; typedef long long ll; typedef pair<int, int> PII; typedef array<int, 3> ARI; const int N=2e5+5,mod=1e9+7,base=448; int s[N], sum[N], ans[N]; int now, cnt, L = 1, R = 0; void add(int id){ sum[s[id]] ++; if(s[id] >= now){cnt ++;} while(cnt - sum[now] >= now + 1){cnt -= sum[now]; now ++;} } void del(int id){ sum[s[id]] --; if(s[id] >= now){cnt --;} while(cnt < now){cnt += sum[now - 1]; now --;} } int main(){ freopen("yy.in", "r", stdin); freopen("yy.out", "w", stdout); ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); int n, q; cin>>n>>q; for(int i=1;i<=n;i++){cin>>s[i];} vector<ARI> Q(q); for(int i=0;i<q;i++){cin>>Q[i][1]>>Q[i][2]; Q[i][0] = i;} sort(Q.begin(), Q.end(), [&](const ARI &a, const ARI &b){ if(a[1] / base != b[1] / base){return (a[1] / base) < (b[1] / base);} else{return ((a[1] / base) % 2 == 0 ? a[2] < b[2] : a[2] > b[2]);} }); for(int i=0;i<q;i++){ int l = Q[i][1], r = Q[i][2], id = Q[i][0]; while(R < r){add(++ R);} while(l < L){add(-- L);} while(R > r){del(R --);} while(l > L){del(L ++);} ans[id] = now; } for(int i=0;i<q;i++){cout<<ans[i]<<"\n";} return 0; }时间复杂度证明: 对于每一个加入或删除的点,其最多只会影响一个位置的值,一个点进行多个上越或下行最多只能释放其前面所积累的势能,故莫队的加入和删除操作均摊时间复杂度 ,总体时间复杂度 ,证毕。
資訊
- ID
- 14
- 時間
- 1200ms
- 記憶體
- 512MiB
- 難度
- 6
- 標籤
- 遞交數
- 37
- 已透過
- 14
- 上傳者
