给定包含 n 个整数的数组,给出两段区间 [l1,r1]、[l2,r2],求两段区间合并、重叠元素只算一次后的所有数字总和
未AC原因:
vector 数组开 n 大小,却用 1~n 下标访问,直接越界 我是猪
AC代码
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main(){
ios::sync_with_stdio(0),cin.tie(0);
int n;
cin>>n;
vector<ll> a(n+1);
for (int i=1;i<=n;i++){
cin>>a[i];
}
int l1,r1,l2,r2;
cin>>l1>>r1>>l2>>r2;
ll ans = 0;
for(int i=l1;i<=r1;i++){
ans+=a[i];
}
for(int i=l2;i<=r2;i++){
if(!(i>=l1 && i<=r1)){
ans+=a[i];
}
}
cout<<ans<<endl;
return 0;
}
第三题:
题目大意:
一共有编号 1∼N 的遥控车,其中有 K 台已经损坏。需要选出一段编号连续、总长度恰好为 B 的遥控车区间,区间里坏掉的车必须修复。求最少需要修复多少辆车(等价于:找长度为 B 的连续区间,区间内损坏车辆数量的最小值)
错误原因:
无法算出答案 0,存在全完好连续区间时直接WA
AC代码
#include <bits/stdc++.h>
using namespace std;
int a[1000005];
int s[1000005];
int main(){
ios::sync_with_stdio(0),cin.tie(0);
int n,b,k;
cin>>n>>b>>k;
for(int i=0;i<k;i++){
int x;
cin>>x;
a[x]=1;
}
for(int i=1;i<=n;i++){
s[i]=s[i-1]+a[i];
}
int ans=k;
for(int i=1;i+b-1<=n;i++){
int r=i+b-1;
int cnt=s[r]-s[i-1];
if(cnt<ans) ans=cnt;
}
cout<<ans<<endl;
return 0;
}
第六题
题目大意:
整行读入,存在栈里面,然后模拟,严格区分弹出元素和仅读取栈顶不弹出两种操作,不能误删原有得分
错误原因:
我没看懂题就在乱写
AC代码:
#include <bits/stdc++.h>
using namespace std;
stack<int> st;
int main(){
string op;
while(cin>>op){
if(op=="C"){
st.pop();
}else if(op=="D"){
int tmp=st.top();
st.push(tmp*2);
}else if(op=="+"){
int x=st.top();
st.pop();
int y=st.top();
st.push(x);
st.push(x+y);
}else{
int num=0;
for(char c:op){
num=num*10+c-'0';
}
st.push(num);
}
}
int sum=0;
while(!st.empty()){
sum+=st.top();
st.pop();
}
cout<<sum<<endl;
return 0;
}