This code works fine on my machine but when i upload it to codechef it gives me a runtime error SIGSEGV. Can anyone please point out the error in my code? This is the question i made it for http://www.codechef.com/problems/ONP/
#include<iostream>
#include<string>
using namespace std;
class stack
{
public:
void push(char a)
{
++top;
arr[top]=a;
}
void pop()
{
top--;
}
void initialize(int size)
{
top=-1;
max=size;
}
bool chckfull()
{
return (top==max-1);
}
bool chckempty()
{
return (top==-1);
}
char front()
{
return arr[top];
}
private:
int top;
int max;
char arr[404];
};
int chckalphanum(char y)
{
if((y>='a')&&(y<='z'))
return 1;
else if ((y>='A')&&(y<'Z'))
return 1;
else if((y>='0')&&(y<='9'))
return 1;
return 0;
}
int pre(char x)
{
if(chckalphanum(x))
return 0;
if(x=='(')
return -1;
else if(x=='^')
return 3;
else if((x=='/')||(x=='*'))
return 2;
else
return 1;
}
int main ()
{
std::ios::sync_with_stdio(false);
string s, s1=")";
char q[404];
int qmax=0,t;
stack prs;
scanf("%d", &t);
while(t--)
{
cin>>s;
prs.initialize(s.length());
prs.push('(');
s=s+s1;
for(int i=0; i<s.length(); i++)
{
if(s[i]=='(')
prs.push('(');
else if(chckalphanum(s[i]))
{
q[qmax]=s[i];
qmax++;
}
else if(s[i]==')')
{
while(prs.front()!='(')
{
q[qmax]=prs.front();
qmax++;
prs.pop();
}
prs.pop();
}
else
{
while(pre(prs.front())>=pre(s[i]))
{
q[qmax]=prs.front();
qmax++;
prs.pop();
}
prs.push(s[i]);
}
}
for(int i=0; i<qmax; i++)
cout<<q[i];
cout<<"\n";
qmax=0;
}
return 0;
}
I just commented out the below line from your solution and it got accepted in codechef.
std::ios::sync_with_stdio(false);
I am not sure if you are aware of what the above line does but I will try to explain to the best of my knowledge. Better answers will definitely follow in due course from the community.
"With stdio synchronization turned off, iostream standard stream objects may operate independently of the standard C streams (although they are not required to), and mixing operations may result in unexpectedly interleaved characters."
Quoting from cppreference.
"Concurrent access to the same stream object may cause data races."
Since you have turned off the synchronization between stdio (C style I/O) and iostream (C++ style I/O)
and you continued using scanf and cin simultaneously interleaved, I suspect you got a runtime error.
For more research, please go through : http://www.cplusplus.com/reference/ios/ios_base/sync_with_stdio/
Hope it clarifies a bit, if not fully. Thanks!
Related
So basically,I am doing a code which searches for an element of a vector inside a vector.While I thought of the approach , implementing it got me a segmentation error. I narrowed down the problem
In the code if I decomment the line in the for loop while commenting the above then all elements of B[i] are being displayed.Why then is a segmentation error being thrown. I think the binary_return is more or less correct and if I replace the line with
binary_return(A,0,A.size(),B[1])
then its working.
Here is the code:
#include<iostream>
#include<vector>
using namespace std;
int binary_return(vector<int> a,int start,int end,int seek)
{
int mid = (start+end)/2;
//cout<<start<<" "<<seek<<" "<<mid;
if(end!=start)
{
if(a[mid]==seek)
{
return mid;
}
else if(a[mid]>seek)
{
return binary_return(a,start,mid,seek);
}
else if(a[mid]<seek)
{
return binary_return(a,mid,end,seek);
}
}
else
return -1;
}
int main()
{
vector<int> A{1,3,6,9,23};
vector<int> B{1,4,23};
cout<<B[0]<<B[1]<<B[2];
for(int i=0;i<B.size();i++)
{
cout<<binary_return(A,0,A.size(),B[i]);
//cout<<binary_return(A,0,A.size(),B[0]);
}
return 1;
}
Your code is not handling the last case correctly and ends up in infinite recursion.
This unfortunately in C++ means that anything can happen (you're not guaranteed to get a meaningful error).
Add a debug print at the beginning of the function and you'll see in which cases you're entering infinite recursion.
You have infinite recursion in third if statment
The correct code if the following:
#include<iostream>
#include<vector>
using namespace std;
int binary_return(vector<int> a,int start,int end,int seek)
{
int mid = (start+end)/2;
//cout<<start<<" "<<seek<<" "<<mid;
if(end!=start)
{
if(a[mid]==seek)
{
return mid;
}
else if(a[mid]>seek)
{
return binary_return(a,start,mid,seek);
}
else if(a[mid]<seek)
{
// In your sample you forgot to add +1 (mid+1) for next start
return binary_return(a,mid+1,end,seek);
}
}
else
return -1;
}
int main()
{
vector<int> A{1,3,6,9,23};
vector<int> B{1,4,23};
for(int i=0;i<B.size();i++)
{
cout<<binary_return(A,0,A.size(),B[i]);
}
return 0;
}
Here is the simple code which I submitted to UVa Online Judging for Qn 227. (Puzzle) I have tested with various test cases including those from debug.org but still the submission yields "wrong answer". If anyone could point out where the error may lie in the code or just give a test case with which the programme will give wrong answer, it will be greatly appreciated.
//puzzle
#define LOCAL
#include <stdio.h>
#include <string.h>
#define MAX 5
int read(char s[MAX][MAX])
{
int blank=0;
for(int i=0;i<5;i++)
{
for(int j=0;j<5;j++)
{
s[i][j]=getchar();
if(i==0&&j==0&&s[i][j]=='Z')
return -1;
else if(s[i][j]==' ')
blank=i*10+j;
}
for(;getchar()!='\n';);
}
return blank;
}
int write(char s[MAX][MAX], int blank)
{
char n;
while((n=getchar())!='0')
{
int c1=(blank/10)%10, c2=blank%10;
if(n=='\n')
continue;
else if(n=='A')
{
if(c1==0)
{
for(;getchar()!='\n';);
return 0;
}
else
{
s[c1][c2]=s[c1-1][c2];
s[c1-1][c2]=' ';
blank-=10;
}
}
else if(n=='B')
{
if(c1==4)
{
for(;getchar()!='\n';);
return 0;
}
else
{
s[c1][c2]=s[c1+1][c2];
s[c1+1][c2]=' ';
blank+=10;
}
}
else if(n=='L')
{
if(c2==0)
{
for(;getchar()!='\n';);
return 0;
}
else
{
s[c1][c2]=s[c1][c2-1];
s[c1][c2-1]=' ';
blank-=1;
}
}
else if(n=='R')
{
if(c2==4)
{
for(;getchar()!='\n';);
return 0;
}
else
{
s[c1][c2]=s[c1][c2+1];
s[c1][c2+1]=' ';
blank+=1;
}
}
else
{
for(;getchar()!='\n';);
return 0;
}
}
for(;getchar()!='\n';);
return 1;
}
int main()
{
#ifdef LOCAL
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
char s[MAX][MAX];
memset(s,'\0',sizeof(s));
int blank, kase=0;
while((blank=read(s))!=-1)
{
if(kase++)
printf("\n");
printf("Puzzle #%d:\n",kase);
if(write(s, blank))
{
for(int i=0;i<5;i++)
{
for(int j=0;j<4;j++)
printf("%c ",s[i][j]);
printf("%c\n",s[i][4]);
}
continue;
}
else
printf("This puzzle has no final configuration.\n");
}
return 0;
}
In the event that the input contains an invalid move, your write() function consumes the rest of that line of input and returns. But the moves for a given puzzle are explicitly permitted to span multiple lines, so your approach does not necessarily consume all of the remaining moves for the puzzle. If it does not, then you start interpreting the remaining unconsumed moves as the start of the next puzzle. The sample cases do not include such an example.
I am getting runtime error mentioned in the title when compiler is in release version and segfault when it is in debug version. I did some research and all I found that it is because of the way I am passing strings to add method. I am not clear so it would great help if anyone describe in simple words why runtime error is occurring.
#include <bits/stdc++.h>
using namespace std;
string add(string a,string b)
{
int lena=a.size()-1,lenb=b.size()-1,carry=0,t;
//segfault occurs here
string tmp;
int m,n;
while(lena>=0||lenb>=0)
{
m=0;
n=0;
if(lena>=0)
{
m=a[lena]-'0';
lena--;
}
if(lenb>=0)
{
n=b[lenb]-'0';
lenb--;
}
t=m+n+carry;
if(t>9)
{
carry=1;
}
else
carry=0;
tmp.push_back('0'+t%10);
}
if(carry)
tmp.push_back('1');
reverse(tmp.begin(),tmp.end());
return tmp;}
class Solution
{
public:
string multiply(string A,string B);
};
string Solution::multiply(string A,string B) {
int i=A.size()-1,j=0,szb=B.size(),c=0,m=0,k=0,n=0;
string sum="",tmp="";
while(i>=0)
{
tmp.clear();
j=szb-1;
k=n;
while(k--)
{
tmp.push_back('0');
}
n++;
c=0;
while(j>=0)
{
m=(A[i]-'0')*(B[j]-'0')+c;
c=m/10;
tmp.push_back((m%10)+'0');
j--;
}
if(c)
tmp.push_back(c+'0');
reverse(tmp.begin(),tmp.end());
sum=add(sum,tmp);
i--;
}
string ans;
for(i=0,j=sum.size();i<j;i++)
{
if(sum[i]!='0')
{
while(i<j)
{
ans.push_back(sum[i]);
i++;
}
}
}
if(ans.size()==0)
return "0";
}
int main()
{
Solution ob;
string s;
s=ob.multiply("99999","99999");
cout<<s<<endl;
}
The error is nothing to do with the way you pass strings to the add function. I'm not sure where you got that idea. The error is here
if(ans.size()==0)
return "0";
it should say
if (ans.size() == 0)
return "0";
else
return ans;
The problem was that if ans.size() > 0 then you weren't returning anything, but your function promised to return a string. This causes a runtime crash.
When I tried your code on my compiler it gave me a warning
warning C4715: 'Solution::multiply' : not all control paths return a value
which says exactly what I said, you don't always return a value from multiply. Your compiler probably says something similar, you should always pay attention to compiler warning messages. They usually do indicate that something is wrong with your code.
I have solved this problem and got AC. My problem is related to equivalence of following two approaches. The first code got accepted, while the second didn't.
As far as I can discern, both are completely equivalent for all the (valid) test cases any human can think of. Am I wrong? If so, what test case can differentiate them?
Code#1 (Accepted one):
#include <cstdio>
bool* M;
bool proc(int N){
for(int j=0;j<=N;j++){
M[j]=false;
}
for(int i=0;i<N;i++){
int a=0;
scanf("%d",&a);
if(a>=N)
return false;
else if(!M[a])
M[a]=true;
else if(!M[N-1-a])
M[N-1-a]=true;
}
bool f = true;
for(int k=0;k<N;k++)
{
f = f && M[k];
}
return f;
}
int main() {
M=new bool[1002];
int num=0;
scanf("%d",&num);
while(num){
int N=0;
scanf("%d",&N);
if(proc(N))
printf("YES\n");
else
printf("NO\n");
num--;
}
return 0;
}
Code #2 (WA):
#include <cstdio>
bool* M;
bool proc(int N){
for(int j=0;j<=N;j++){
M[j]=false;
}
for(int i=0;i<N;i++){
int a=0;
scanf("%d",&a);
if(a>=N)
return false;
else if(!M[a])
M[a]=true;
else if(!M[N-1-a])
M[N-1-a]=true;
else
return false;
}
return true;
}
int main() {
//Exactly same as code#1
}
The bug has nothing to do with the algorithm itself—it's very possible both the algorithms are correct. But the second implementation is wrong.
When you reach a test case which should return NO, you exit the function prematurely. Which means there are some numbers from the current test case left unread in the input, which of course confuses further reading thoroughly. This means the bug only manifests when T > 1.
i have a problem with my program. It should be program that recognize palindome through the stack. Everything works great, only thing that don't work is printing stacks(original and reversed) after the funcion is done.
Here is my entire code, and the problem is at case d and e:
#include <iostream>
using namespace std;
const int MAXSTACK = 21;
class stack {
private:
int stop;
char stk[MAXSTACK];
public:
stack();
~stack();
stack(const stack& s);
void push(const char c);
char pop();
char top(void);
int emptystack(void);
int fullstack(void);
void stack_print(void);
int stack::create(void);
};
stack::stack()
{
stop = 0;
}
stack::~stack() { }
stack::stack(const stack& s)
{
stop = s.stop;
strcpy(stk,s.stk);
}
void stack::push(const char c)
{
stk[stop++] = c;
}
char stack::pop()
{
return stop--;
}
char stack::top(void)
{
return stk[stop - 1];
}
int stack::emptystack(void)
{
return !stop;
}
int stack::fullstack(void)
{
return stop == MAXSTACK;
}
void stack::stack_print(void)
{
for (int i=0; i<stop; i++)
cout<<stk[i];
cout<<endl;
}
int stack::create(void)
{
return !stop;
}
char menu()
{
char volba;
cout<<"\n";
cout<<" **********.\n";
cout<<"\n";
cout<<" a ... make new containers\n";
cout<<" b ... delete content\n";
cout<<" c ... enter string\n";
cout<<" d ... print on screen first stack\n";
cout<<" e ... print on screen first stack\n";
cout<<" f ... is it palindrom\n";
cout<<" x ... exit\n";
cout<<"\n your choice : ";
cin >> volba;
return volba;
}
int main() {
char palindrome[MAXSTACK];
char volba;
stack original,reversed;
int stackitems = 0,i;
//cin.getline(palindrome,MAXSTACK);
do{
volba = menu();
switch (volba)
{
case'a':
{
original.create();
reversed.create();
cout<<"done'";
break;
}
case'b':
{
original.emptystack();
reversed.emptystack();
cout<<"empty";
break;
}
case'c':
{
cout<<"enter your string"<<endl;
cin.get();
//cin.get();
cin.getline(palindrome,MAXSTACK);
for(int o = 0; o < strlen(palindrome); o++)
if (isalpha(palindrome[o]))
{
original.push(tolower(palindrome[o]));
stackitems++;
}
original.stack_print();
break;
}
case'd':
{
original.~stack();
for(int g = 0; g < strlen(palindrome); g++)
original.push(tolower(palindrome[g]));
original.stack_print();
}
/*//cin.getline(palindrome,MAXSTACK);
for(int g = 0; g < strlen(palindrome); g++)
if (isalpha(palindrome[g]))
{
original.push(tolower(palindrome[g]));
stackitems++;
}
}
original.stack_print();*/
break;
/*{
cout<<"original: ";
original.stack_print();
break;
}*/
break;
case'e':
{
cout<<"reversed:"<<endl;
for( i = 0; i < stackitems; i++) {
reversed.push(original.top());
original.pop();
}
reversed.stack_print();
}
break;
case'f':
{
for( i = 0; i < stackitems / 2; i++) {
reversed.push(original.top());
original.pop();
}
if (stackitems % 2)
original.pop();
while (!original.emptystack()) {
if (original.top() != reversed.top()) break;
original.pop(); reversed.pop();
}
if (original.emptystack())
cout << "it is palindrom\n";
else
cout << "not palindrom\n";
break;
}
default:cout<<"!??!";
}
} while(volba!='x');
}
You've explicitly called your stack's destructor. There is almost never a good reason to do this. If the stack is a local ("on the stack", hee hee), the compile will do it for you. If it's on the heap, created with new, call delete on it, which will cause the compiler to call the destructor.
case'd':
{
original.~stack();
You have commented palindrome reading :)
//cin.getline(palindrome,MAXSTACK);
There are a few things I would like to respond with. First, I think GMan, tpdi, and Vinay all have good points. This FAQ explains why calling the destructor on a local variable is a bad idea.
I realize this is just a simple homework problem and you are probably just trying to keep your stack class lightweight, but you might consider using a container class instead of an array of characters in your stack class.
Next, I'm not sure your emptystack and create functions are doing what you think they are doing. When you declare your original and reversed stack classes in the main program the memory is allocated for your internal character array. It's not really necessary in this case to have a create function. Perhaps if you were allocating memory on the heap for your character array, you would put that code into the create function (if you chose to leave it out of the constructor for some reason), but that's not the case here.
Similarly, emptystack isn't really doing anything. It would be better to have empty stack set the stop member variable to 0. At least that way the stack would appear to be empty the next time someone tried to use it.
There's a lot more that could be said about this class, but it might be better if you tried some of the suggestions here like using the std::stack and debugging. This is, after all, your homework assignment: it will help you a lot more in the future if you find the solution yourself!