题解:P12656 [KOI 2023 Round 1] 道具获取
这是道前缀和 + 二分 + 模拟的题。
思路:
- 像建图那样,把输入的
x 、y 、w 加入,一条x \to (y, w) ,一条y \to (x, w) 。 - 将箱子排序,前缀和预处理每行每列的有箱子的位置。
- 按题意模拟,计算时用二分查找找到第一个
\ge l 和最后一个\le r 的位置,然后前缀相减。
能用二分的原因:数组已按升序排序。
Tips:注意起点位置的箱子不能拿,终点位置的可以拿。
时间复杂度:
最后放个代码:
//#pragma GCC optimize("Ofast,unroll-loops")
#pragma GCC target("avx2,fma")
#include<bits/stdc++.h>
using namespace std;
#define F(i,j,k,l) for(int i=(j);i<=(k);i+=(l))
#define f(i,j,k,l) for(int i=(j);i>=(k);i-=(l))
#define W(i) while(i)
#define A auto
#define ot float
#define FO(x,a) for(int x:a)
#define Fo(x,a) for(A x:a)
#define el "\n"
#define ull unsigned long long
#define ll long long
#define in __int128
#define pii pair<int,int>
#define pll pair<ll,ll>
#define pil pair<int,ll>
#define dle double
#define ld long double
#define imax INT_MAX
#define imin INT_MIN
#define debug(x) cerr<<#x<<" "<<x<<"\n";
const int N=2e5+10,M=1<<20,K=2e5;
char buf[M],*p1=buf,*p2=buf,out[M],*p3=out;
#define gc() (p1==p2?(p2=(p1=buf)+fread(buf,1,M,stdin),p1==p2?EOF:*p1++):*p1++)
#define flush() (fwrite(out,1,p3-out,stdout),p3=out)
#define pc(c) (p3==(out+M)?(flush(),*p3++=(c)):*p3++=(c))
inline long long read(){
long long x=0,f=1;
char ch=gc();
W(!isdigit(ch)){
if(ch=='-') f=-1;
ch=gc();
}
W(isdigit(ch)){
x=x*10+(ch-'0');
ch=gc();
}
return x*f;
}
inline void write(long long x){
if(x<0){
pc('-');
x=-x;
}
if(x==0){
pc('0');
return;
}
char s[25];
int len=0;
W(x){
s[len++]=char('0'+x%10);
x/=10;
}
W(len) pc(s[--len]);
return;
}
vector<int> pos[N*2];
vector<ll> sum[N*2];
int n,q;
vector<pii> x[N],y[N];
inline void pre(int p,const vector<pii> &tmp){
vector<pii> k=tmp;
sort(k.begin(),k.end());
int siz=k.size();
pos[p].resize(siz),sum[p].resize(siz);
F(i,0,siz-1,1) pos[p][i]=k[i].first,sum[p][i]=k[i].second+(i>0?sum[p][i-1]:0);
}
inline ll calc(int p,int l,int r){
if(l>r||pos[p].empty()) return 0;
auto posl=lower_bound(pos[p].begin(),pos[p].end(),l)-pos[p].begin();
auto posr=upper_bound(pos[p].begin(),pos[p].end(),r)-pos[p].begin()-1;
if(posl>posr) return 0;
return (sum[p][posr]-((posl!=0?sum[p][posl-1]:0)));
}
inline void input(){
n=read(),q=read();
F(i,1,n,1){
int u=read(),v=read(),w=read();
x[u].push_back({v,w}),y[v].push_back({u,w});
}
F(i,1,K,1){
pre(i,x[i]);
pre(i+K,y[i]);
}
}
inline void output(){
int x1=1,y1=1;
ll val=0;
W(q--){
int d=read(),v=read();
//坑点:起点的东西不能拿
if(d==0){
val+=calc(y1+K,x1+1,x1+v);
x1+=v;
}else if(d==1){
val+=calc(x1,y1+1,y1+v);
y1+=v;
}else if(d==2){
val+=calc(y1+K,x1-v,x1-1);
x1-=v;
}else{
val+=calc(x1,y1-v,y1-1);
y1-=v;
}
}
write(val);
}
inline void solve(){
input();
output();
return;
}
int main(){
int _=1;
while(_--) solve();
flush();
return 0;
}