数组的整体操作
小J手下有N名士兵,小J每天有以下三种操作
1 x:让所有的士兵的武力全变成x
2 i x: 将第i个士兵的武力加上x
3 i:查询第i个士兵的武力值
Format
Input
一行给出N,代表N个士兵
第二行给出N个数字,代表士兵最开始的武力值
第三行给出Q,代表共Q个操作
接下来Q行,描述Q个操作
N<=2e5
Q<=2e5
Output
如题
Samples
输入数据 1
5
3 1 4 1 5
6
3 2
2 3 4
3 3
1 1
2 3 4
3 3
输出数据 1
1
8
5
Sol
如果使用数组来完成,则开个lazy标记
对于整体赋值的操作,记下操作的时间点las及加的值val
对于单独赋值的操作,对于每个元素p开个tag记对其整体赋值的时间点
如果tag[p]<las,其追加上从前的整体赋值的操作
然后加上这次单独进行操作的值
对于打印操作,同上
#include <bits/stdc++.h> #define int long long using namespace std; int a[1000000],tag[1000000]; signed main() { int n,q,las=0,val; cin>>n; for(int i=1; i<=n; i++) cin>>a[i]; cin>>q; for(int i=1; i<=q; i++) { int op; cin>>op; if(op==1) { cin>>val; las=i; } if(op==2) { int p,x; cin>>p>>x; if(tag[p]<las) { tag[p]=las; a[p]=val; } a[p]+=x; } if(op==3) { int p; cin>>p; if(tag[p]<las) { tag[p]=las; a[p]=val; } cout<<a[p]<<endl; } } return 0; }
使用map
#include<bits/stdc++.h> using namespace std; map<int,long long>a; int main(){ cin.tie(0); ios::sync_with_stdio(0); long long n,every=0; cin>>n; for(int i=1;i<=n;i++) cin>>a[i]; long long q; cin>>q; while(q--){ long long t; cin>>t; if(t==1) //让所有的士兵的武力全变成x { int x; cin>>x; every=x; a.clear(); }if(t==2)//将第i个士兵的武力加上x { int j,x; cin>>j>>x; if(a[j]==0) a[j]=every; a[j]+=x; } if(t==3) { int j; cin>>j; if(a[j]==0) cout<<every<<endl; else cout<<a[j]<<endl; } } return 0; }