i used this code and it gave me right output for given test cases but it is still showing wrong answer.I have checked the editorial and it seems like my logic is right.can somebody help me
#include <iostream>
using namespace std;
int main() {
// your code goes here
long long int t;
cin>>t;
while(t--)
{
long long int k;
long long int n;
cin>>n>>k;
string s;
cin>>s;
long long int length;
for(long long int i=0;i<n-1;i++)
{
length=length+1+(s[i]==s[i+1]);
}
while(k--)
{
long long int q;
cin>>q;q--;
if(s[q]=='1')
s[q]='0';
else
s[q]='1';
if(q==0)
{
if(s[q]==s[q+1])
length=length+1;
else
length=length-1;
}
else if(q==n-1)
{
if(s[q]==s[q-1])
length=length+1;
else
length=length-1;
}
else{
if(s[q]==s[q+1])
length++;
if(s[q]==s[q-1])
length++;
if(s[q]!=s[q+1])
length--;
if(s[q]!=s[q-1])
length--;
}
cout<<length<<endl;
}
}
return 0;
}
error even after i adjusted it for both output=1 and output=0
#include <iostream>
using namespace std;
int main() {
// your code goes here
int t;
cin>>t;
while(t--)
{
long long int k;
long long int n;
cin>>n>>k;
if(n==1)
cout<<0<<endl;
else
{
string s;
cin>>s;
long long int length;
for(long long int i=0;i<n-1;i++)
{
length=length+1+(s[i]==s[i+1]);
}
while(k--)
{
long long int q;
cin>>q;q--;
if(s[q]=='1')
s[q]='0';
else
s[q]='1';
if(q==0)
{
if(s[q]==s[q+1])
length=length+1;
else
length=length-1;
}
else if(q==n-1)
{
if(s[q]==s[q-1])
length=length+1;
else
length=length-1;
}
else{
if(s[q]==s[q+1])
length++;
if(s[q]==s[q-1])
length++;
if(s[q]!=s[q+1])
length--;
if(s[q]!=s[q-1])
length--;
}
cout<<length<<endl;
}
}
}
return 0;
}
still wrong answer
i tried for 0 0 0 and 1 1 1 both
#include <iostream>
using namespace std;
int main() {
// your code goes here
int t;
cin>>t;
while(t--)
{
long long int k;
long long int n;
cin>>n>>k;
string s;
cin>>s;
long long int length;
for(long long int i=0;i<n-1;i++)
{
length=length+1+(s[i]==s[i+1]);
}
while(k--)
{
long long int q;
cin>>q;q--;
if(s[q]=='1')
s[q]='0';
else
s[q]='1';
if(n==1)
cout<<0<<endl;
else
{
if(q==0)
{
if(s[q]==s[q+1])
length=length+1;
else
length=length-1;
}
else if(q==n-1)
{
if(s[q]==s[q-1])
length=length+1;
else
length=length-1;
}
else{
if(s[q]==s[q+1])
length++;
if(s[q]==s[q-1])
length++;
if(s[q]!=s[q+1])
length--;
if(s[q]!=s[q-1])
length--;
}
cout<<length<<endl;
}
}
}
return 0;
}
Reading compiler warnings would have exposed this straight away:
[simon@simon-laptop][08:44:15]
[~/devel/hackerrank/otherpeoples]>./compile-latest-cpp.sh
Compiling abhinav_700-CHARGES.cpp
+ g++ -std=c++14 abhinav_700-CHARGES.cpp -O3 -g3 -Wall -Wextra -Wconversion -DONLINE_JUDGE -D_GLIBCXX_DEBUG -fsanitize=undefined -ftrapv
abhinav_700-CHARGES.cpp: In function ‘int main()’:
abhinav_700-CHARGES.cpp:21:26: warning: ‘length’ may be used uninitialized in this function [-Wmaybe-uninitialized]
length=length+1+(s[i]==s[i+1]);
~~~~~~^~
+ set +x
Successful