D - 敌兵布阵
1.题意:
2.题解:
string好像不能用scanf输入,会报错,同理printf
减一个数=加他的相反数
3.ac代码:
#include<bits/stdc++.h>
#include<string>
typedef long long ll;
using namespace std;
const int N=1e6+10;
ll a[N];
string s;
struct segmentTree{
#define lson (node<<1)
#define rson (node<<1|1)
ll sum[N<<2],lazy[N<<2];
void spread(int node,int l,int r){//下放
int mid=(r+l)>>1;
if(lazy[node]!=0){
sum[lson]+=1ll*lazy[node]*(mid-l+1);
sum[rson]+=1ll*lazy[node]*(r-(mid+1)+1);
lazy[lson]+=lazy[node];
lazy[rson]+=lazy[node];
lazy[node]=0;
}
}
void pushup(int node){//回溯
sum[node]=sum[lson]+sum[rson];
}
void build(int node,int l,int r){//创建树
lazy[node]=0;
if(l==r){
sum[node]=a[l];
return;
}
int mid=l+r>>1;
build(lson,l,mid);
build(rson,mid+1,r);
pushup(node);
}
void change(int node,int l,int r,int idx,int x){//单点修改
if(l==r){
sum[node]+=x;
return;
}
spread(node,l,r);
int mid=l+r>>1;
if(idx<=mid){
change(lson,l,mid,idx,x);
}else{
change(rson,mid+1,r,idx,x);
}
pushup(node);
}
void change(int node,int l,int r,int L,int R,int x){//区间修改
if(l==L&&r==R){
sum[node]+=1ll*x*(r-l+1);
lazy[node]+=x;
return ;
}
spread(node,l,r);
int mid=l+r>>1;
if(R<=mid){
change(lson,l,mid,L,R,x);
}else if(L>mid){
change(rson,mid+1,r,L,R,x);
}else{
change(lson,l,mid,L,mid,x);
change(rson,mid+1,r,mid+1,R,x);
}
pushup(node);
}
ll query(int node,int l,int r,int L,int R){
if(l==L&&r==R){
return sum[node];
}
spread(node,l,r);
int mid=l+r>>1;
if(R<=mid)
return query(lson,l,mid,L,R);
else if(L>mid)
return query(rson,mid+1,r,L,R);
else{
ll ans=0;
ans+=query(lson,l,mid,L,mid);
ans+=query(rson,mid+1,r,mid+1,R);
return ans;
}
}
ll query(int node,int l,int r,int idx){//单点查询
if(l==r){
return sum[node];
}
spread(node,l,r);
int mid=r+l>>1;
if(idx<=mid){
return query(lson,l,mid,idx);
}else{
return query(rson,mid+1,r,idx);
}
}
}tree;
int main(){
int t;
int n;
scanf("%d",&t);
int num=0;
while(t--){
num++;
scanf("%d",&n);
for(int i=1;i<=n;i++){
scanf("%d",&a[i]);
}
tree.build(1,1,n);
int i,j;
printf("Case %d:\n",num);
while(cin>>s){
if(s=="End"){
break;
}
if(s=="Query"){
scanf("%d%d",&i,&j);
ll ans=tree.query(1,1,n,i,j);
printf("%lld\n",ans);
}else if(s=="Add"){
scanf("%d%d",&i,&j);
tree.change(1,1,n,i,j);
}else if(s=="Sub"){
scanf("%d%d",&i,&j);
tree.change(1,1,n,i,-j);
}
}
}
}
3192. 出现次数最多的数
1.题意:
2.题解:
wa了好几发,要记住,下面找最大的,那个数的范围是1~N
3.ac代码:
#include<bits/stdc++.h>
typedef long long ll;
using namespace std;
const int N=1e6+10;
int c[N];
int main(){
int n;
cin>>n;
int res=0;
for(int i=1;i<=n;i++){
int x;
cin>>x;
c[x]++;
}
for(int i=1;i<N;i++){
if(c[i]>c[res]){
res=i;
}
}
cout<<res<<endl;
}
781. 森林中的兔子
1.题意:
2.题解:
偏思考题+向上取整
实现向上取整:n/(x+1)的向上取整可以转化为 (n + x) / (x + 1)
即:(n+x-1)/x,可实现向上取整
3.ac代码:
class Solution {
public:
int numRabbits(vector<int>& answers) {
map<int,int> cnt;
for(auto x:answers){
cnt[x]++;
}
int res=0;
for(auto[a,b]:cnt){
res+=(a+b)/(a+1)*(a+1);
}
return res;
}
};