很明显的 DP。
设 为考虑前 个数且选择第 个数的花费最小值。显然 。
现在我们看看如何计算此集合。显然对于每一个限制条件的 , 至少要从 开始,枚举到 ,因为这样才能保证这个区间取到数了。当然为了确保前面区间都取到数,我们需要满足所有条件。设 ,代表选上 数后前面区间都选到的 集合为 ,那么 为前面所有 对应的 的最大值。所以只需要对每组限制条件打标记(),DP 时更新 并转移,就可以 实现了。
下面我们考虑如何优化。注意到取的是集合的最小值,而第 次我们其实只需要删除集合中:
- 。
- 原来的 到更新的 下标的 值。
容易发现每个 最多只会进入一次、出去一次集合。而我们要求集合中最小值,所以可以用 std::multiset(这里不用 set,因为可能有重复 )。时间复杂度 ,可以通过。
考试的时候写的代码,有点丑:
#include<bits/stdc++.h>
#define int long long
#define rep(i,a,b) for(int i(a);i<=(b);++i)
#define req(i,a,b) for(int i(a);i>=(b);--i)
using namespace std;
char buf[1<<23],*p1=buf,*p2=buf,ubuf[1<<23],*u=ubuf;
#define getchar() (p1==p2&&(p2=(p1=buf)+fread(buf,1,1<<21,stdin),p1==p2)?EOF:*p1++)
template<typename TP> inline TP read(TP &num)
{
TP x=0;
int f=0;
char ch=getchar();
while(ch<48||ch>57) f|=ch=='-',ch=getchar();
while(48<=ch&&ch<=57) x=(x<<1)+(x<<3)+(ch^48),ch=getchar();
return num=f?-x:x;
}
template<typename ...Args> inline void read(Args &...args)
{
(read(args),...);
}
template<typename TP> inline void write(TP x)
{
(x<0)?(putchar('-'),x=-x):0;
(x>9)?(write(x/10),0):0;
putchar((x%10)^48);
}
template<typename TP> inline void writeln(TP x)
{
write<TP>(x);
puts("");
}
int T,n,a[500001],q,l[500001],r[500001],f[500001],st;
int id[500001];
basic_string<int> lim[500001];
multiset<int> s;
// f[i] denotes the minimum of (ensure previous conditions are satisfied, and choose i-th number)
inline void solve()
{
st=0;
rep(i,1,n)
{
f[i]=9e18;
if(lim[i].size()) st=max(st,lim[i].back());
rep(j,st,i-1) f[i]=min(f[i],f[j]);
f[i]+=a[i];
}
int ans=9e18;
rep(i,l[id[q]],r[id[q]]) ans=min(ans,f[i]);
writeln(ans);
}
signed main()
{
read(T);
while(T--)
{
read(n);
rep(i,1,n) read(a[i]),lim[i].clear(),f[i]=0;
read(q);
rep(i,1,q)
{
read(l[i],r[i]);
lim[r[i]+1]+=l[i];
}
iota(id+1,id+q+1,1);
sort(id+1,id+q+1,[](int x,int y){return l[x]<l[y];});
rep(i,1,n) sort(lim[i].begin(),lim[i].end());
st=0;
if(n*n<=1e8)
{
solve();
continue;
// return 0;
}
s.clear();
rep(i,1,n)
{
s.emplace(f[i-1]);
if(lim[i].size())
{
int ost=st;
st=max(st,lim[i].back());
// st ~ i-1
rep(j,ost,st-1) s.erase(s.find(f[j]));
}
f[i]=(s.size()?*s.begin():0)+a[i];
}
int ans=9e18;
rep(i,l[id[q]],r[id[q]]) ans=min(ans,f[i]);
writeln(ans);
}
return 0;
}