对于 this问题我需要做多个查询所以我用了一个for循环
#include<bits/stdc++.h>
using namespace std;
int main(){
vector<int>ans; //vector to store the ans
string s,e; //real dna and virus dna
cin>>s;
int q,start,match=0; // no. of queries, starting value of the query, var to store matching occurence
unsigned int step=0; //var to keep count of virus dna iteration
cin>>q;
for(int i=0;i<q;i++){//loop to iterate q times
cin>>start;
int l,r,x,c;
if(start==2){ // for 2nd type query
cin>>l>>r>>e;
for(int i=l-1;i<=r-1;i++){
if(s[i]==e[step]){
match+=1;
}
step+=1;
if(step== e.length()){
step=0; //starting again from start of virus
}
}
}
ans.push_back(match);
match=0; //reintializing value for next query
if(start==1){ //for 1st type query
cin>>x>>c;
s[x-1]=c; //replacing char at x-1 with c
}
}
for(int j=0;j<ans.size();j++){ //loop for ans output
cout<<ans[j]<<endl;
}
return 0;
}
但它在应该终止之前就终止了,例如:对于这个输入,
ATGCATGC
4
2 1 8 ATGC
2 2 6 TTT
1 4 T
2 2 6 TA
它将在第 5 行停止并打印 8 ,2 ,0, 0 而它应该是 8, 2, 4。如果我在没有循环的情况下执行单个查询,一切正常,但任何类型的循环都不起作用。请帮助。此外,任何更有效地解决此类问题的建议都会对我很有帮助。
最佳答案
代码中更大的问题是变量 c
被定义为 int
int l,r,x,c;
当接收到字符而非整数时(T
,在您的示例中),因此应定义为 char
int l,r,x;
char c;
如果c
是int
,当你发送4 T
到
cin>>x>>c;
x
收到 4,c
没有收到 T
(T
不是有效的 int
) 所以开始外循环的下一次迭代,称为
cin>>start;
当 T
保留在缓冲区中时; start
是整数,所以有同样的问题,程序结束。
而且,正如 soon 所指出的,ans.push_back()
应该在第一个 if 中。现在,还为以 1
开头的行添加了一个值(零)。
关于c++ - 多个查询的循环过早终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45236423/