題意:給你n個區間,m個詢問,對于每個詢問求最少可以用多少個區間完成覆寫,區間可以重疊。
思路:倍增法,f[i][j]表示i點連續向後擴充2^j個區間後可以達到的最後位置,預處理O(nlogn),注意一下細節。
代碼:
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int N = 1e6+10;
int n,m,ans,a[N],mx,f[N][21],x,y;
int main()
{
cin>>n>>m;
for(int i=1; i<=n; i++)
{
cin>>x>>y;
a[x]=max(a[x],y);///注意有公共起點
mx=max(mx,y);
}
for(int i=1; i<=mx; i++) a[i]=max(a[i-1],a[i]);
for(int i=0; i<=mx; i++) f[i][0]=a[i];
///倍增
for(int j=1; j<=20; j++)
for(int i=0; i<=mx; i++)
f[i][j]=f[f[i][j-1]][j-1];
while(m--)
{
ans=0;
cin>>x>>y;
for(int i=20; i>=0; i--) if(f[x][i]<y) ans+=1<<i,x=f[x][i];
if(a[x]<y) cout<<-1<<endl;
else cout<<ans+1<<endl;
}
return 0;
}