题解:P14046 [SDCPC 2019] BaoBao Loves Reading
前言
第一次写蓝题解!
题目解析
很显然我们需要在每一个时刻同时来计算所有的
为了区分,我们把原本的答案
不妨我们从左到右遍历,且认为当前遍历到了位置
这里会有问题:对于一次取一本书桌上有的书,其目前占用的长度是不变的,但按照我们的思路其多占用了长度。我们认真考虑,发现对于 1 2 3 4 a_i 5 6 7 8。
然后取后变为
1 2 3 4 5 6 7 8 a_i。显然取书时间
其次考虑数据结构的使用。显然
正解代码
#include<bits/stdc++.h>
#define int long long
using namespace std;
class BIT
{
private:
int lowbit(int x)
{
return (x&-x);
}
public:
int n;
vector<int> t;
BIT(int sz)
{
t.resize(sz+4);
n=sz;
}
BIT(){}
void add(int id,int k) //加入一个数字
{
while(id<=n)
{
t[id]+=k;
id+=lowbit(id);
}
}
int query(int id) //查询前缀和
{
int ans=0;
while(id>=1)
{
ans+=t[id];
id-=lowbit(id);
}
return ans;
}
};
signed main()
{
int t;
cin>>t;
while(t--)
{
BIT ft(100005);//ft维护f的修正错误
BIT ans(100005);//ans维护答案
int a[100005]={0};
int f[100005]={0};
int n;
cin>>n;
for(int i=1;i<=n;i++) cin>>a[i];
for(int i=1;i<=n;i++)
{
if(!f[a[i]]) //a[i]之前没出现过
{
ans.add(1,1);
}
else //出现过了
{
//计算答案
ans.add(1,1);
ans.add(i-(f[a[i]]+ft.query(f[a[i]])),-1);
//修正错误
ft.add(1,1);
ft.add(f[a[i]],-1);
}
f[a[i]]=i;
}
for(int i=1;i<=n;i++)
{
cout<<ans.query(i);
if(i!=n) cout<<" ";
}
cout<<"\n";
}
return 0;
}