getting TLE from mouse maze in c++ - c++

I keep getting TLE in this question.I have tried to use scanf printf instead of cin cout but it didnt work.Then,I tried another question which has same
description,the only different is input N which means test case change from 1000 to 10^6.However, I got all AC there.I just cant figure out why.
following is the question
Description
Write a program that simulates a mouse in a maze. The program must count the steps taken by the mouse from the starting point to the final point.
The maze type is shown in following figure:
S$###
$$#$$
$$$##
##$$F
it consists of S (starting point), #(walls), $(road) and F (final point).
In above case, it needs 7 steps from S to F as following figure,
S$###
$$#$$
$$$##
##$$F
and the mouse can move in the four directions: up, down, left, right. There may be more than one way to reach final point, the program only need to print the least steps.
If there is no way from S to F, then print -1.
Input
The first line has an integer N(1<=N<=1000), which means the number of test cases.
For each case, the first line has two integers. The first and second integers R and C (3<=R, C<=500) represent the numbers of rows and columns of the maze, respectively. The total number of elements in the maze is thus R x C.
The following R lines, each containing C characters, specify the elements of the maze.
Output
Print out the least steps for each case, and there is a new line character at the end of each line.
Sample Input
3
4 5
S$###
$$#$$
$$$##
##$$F
4 5
S$$##
#$$$#
#$#$#
#$$$F
4 5
##S$#
$##$$
$$$##
#F###
Sample Output
7
7
-1
following is my code
#include <iostream>
#include <climits>
using namespace std;
int least_step;
void maze(char a[501][501],int,int,int,int,int);
#define wall '#'
int main(){
int ncase;
cin>>ncase;
char a[501][501];
while(ncase--){
int num1,num2;
cin>>num1>>num2;
least_step = INT_MAX;
int si,sj;
for(int i=0;i<num1;i++){
for(int j=0;j<num2;j++){
cin >> a[i][j];
if(a[i][j]=='S'){
si = i;
sj = j;
}
}
}
maze(a,si,sj,num1,num2,0);
if(least_step==INT_MAX){
least_step = -1;
}
cout<<least_step<<endl;
}
return 0;
}
void maze(char a[501][501],int i,int j,int num1,int num2,int step){
if(a[i][j] == 'F'){
if(step<least_step){
least_step = step;
}
return;
}
a[i][j] = wall;
if(i+1<num1&&a[i+1][j] != wall){
maze(a,i+1,j,num1,num2,step+1);
}
if(j+1<num2&&a[i][j+1] != wall){
maze(a,i,j+1,num1,num2,step+1);
}
if(i-1>=0&&a[i-1][j] != wall){
maze(a,i-1,j,num1,num2,step+1);
}
if(j-1>=0&&a[i][j-1] != wall){
maze(a,i,j-1,num1,num2,step+1);
}
a[i][j] = '$';
return;
}

Related

My program doesn't end

I'm new too c++ and I had to design a program that determines the first four triangular square numbers and the output is exactly how I want it to be, but it wont quit after its printed the first four. I can't figure out what it could be. I can't CTRL C because I will get points taken off. What is the issue here?
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
//Prints name line
cout<<"*********** BY: ********"<<endl;
//Initializing
const int HOW_MANY=4;
int num=1;
int tsn=0;
int z=1;
int x=0;
//How many TSN it will find and be printed
while (x<=HOW_MANY)
{
//
int sum=0;
for (int y=0;y<512;y++)
{
sum+=y;
tsn=pow(num,2);
//Tests if the numbers are TSN
if ((sum==tsn) || (num+1)/sqrt(num)==sqrt(num))
{
//Prints 1-HOW_MANY TSN and what they are
cout<<"Square Triangular Number "<< z <<" is: "<< tsn <<endl;
z++;
x++;
}
}
num++;
}
return 0;
}
If x = 0 then instead of while (x<=HOW_MANY) you need write while (x<HOW_MANY).
x begins at 0. Every time you find and print a number it gets incremented. You'll continue this, so long as x<=HOW_MANY.
You say your program finds 4 numbers but keeps running. After 4 hits, x will be 4. Is 4 <= 4? The answer is yes, so your program keeps running.
Either change the condition to x < HOW_MANY, or initialize x to 1.
EDIT
Did a little leg work, it turns out the sum of all the numbers in the range [1,512] is 131328. The 5th square triangle number is 1413721.
This means after you find the fourth triangle number, you will never sum high enough to find the next one. This will result in the infinite loop you're seeing.
The answer above is still the correct fix, but this is the reason you end up with an infinite loop.
for should be used for iteration and while should be used for condition testing.
The problem, as has been noted, is that your x condition variable is never being incremented to get you out of the outer loop. That's a logic error that can be avoided by using the appropriate control structure for the job.

Reading Matrix Market file C++ issues

I'm trying to read and use a matrix market file, but my current attempts haven't produced anything. I'm extremely new to C++ so be gentle. Here's what I've got so far:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <fstream>
#include <algorithm>
using namespace std;
int main()
{
ifstream f("GX30.mtx");
int m,n,l;
while(f.peek()=='%') f.ignore(2048, '\n');
f>>m>>n>>l;
cout<<l;
int I[m],J[n],val[l];
int mat[m][n];
for(int i=1;i<=l;i++)
{
f>>I[i]>>J[i]>>val[i];
}
for(int k=1; k<=l;k++)
{
mat[I[k]][J[k]]=val[k];
cout<<"test";
}}
My test output produces nothing, and none of the variables determining the matrix parameters initialize properly. The first few lines from the file I'm reading from are as follows:
%%MatrixMarket matrix coordinate integer general
%% X {5,5} [[30,8,3]] [ (b*a^-1)^3 ]
12 30 60
1 1 1
1 3 1
1 4 1
The first line not proceeded by % indicates the number of rows, then columns, then lastly the number of non zero entries (I think)
Then the following lines index the row and column position of each entry, with its corresponding value.
There are few issues you need to fix.
The main problem is how you access arrays. Array index starts from 0, not 1. Array sizes are different in your application too.
I[m],J[n],val[l];
m, n, l are not equal so you go beyond boundaries of two arrays:
for(int i=1;i<=l;i++)
for(int k=1; k<=l;k++)
You code most likely causes an access violation and crashes, hence you don't even see the result of cout<<l; operation.
You shouldn't access all array from a single loop like you do. Something like the following is alright.
for (int i = 0; i < l; ++i)
{
val[i] ... // val array, not I or J here
}
Also, Matrix Market allows for float values but you are using integers.
Yet another thing: Lines may be separated by "\r", "\n" and "\r\n" but you expect '\n'. Does Matrix Market format specify anything or it relies on OS conventions? If lines are separated with '\r' then your code may not work:
while(f.peek()=='%') f.ignore(2048, '\n');

ARRAYS DEBUGGING incorrect outputs, complex algorithm

I made this algorithm, i was debugging it to see why it wasnt working, but then i started getting weird stuff while printing arrays at the end of each cycle to see where the problem first occurred.
At a first glance, it seemed my while cycles didn't take into consideration the last array value, but i dunno...
all info about algorithm and everything is in the source.
What i'd like to understand is, primarily, the answer to this question:
Why does the output change sometimes?? If i run the program, 60-70% of the time i get answer 14 (which should be wrong), but some other times i get weird stuff as the result...why??
how can i debug the code if i keep getting different results....plus, if i compile for release and not debug (running codeblocks under latest gcc available in debian sid here), i get most of the times 9 as result.
CODE:
#include <iostream>
#include <vector>
/*void print_array
{
std::cout<<" ( ";
for (int i = 0; i < n; i++) { std::cout<<array[i]<<" "; }
std::cout<<")"<<std::endl;
}*/
///this algorithm must take an array of elements and return the maximum achievable sum
///within any of the sub-arrays (or sub-segments) of the array (the sum must be composed of adjacent numbers within the array)
///it will squeeze the array ...(...positive numbers...)(...negative numbers...)(...positive numbers...)...
///into ...(positive number)(negative number)(positive number)...
///then it will 'remove' any negative numbers in case it would be convienent so that the sum between 2 positive numbers
///separated by 1 negative number would result in the highest achievable number, like this:
// -- (3,-4,4) if u do 'remove' the negative number in order to unite the positive ones, i will get 3-4+4=3. So it would
// be better not to remove the negative number, and let 4 be the highest number achievable, without any sums
// -- (3,-1,4) in this case removing -1 will result in 3-1+4=6, 6 is bigger than both 3 and 4, so it would be convienent to remove the
// negative number and sum all of the three up into one number
///so what this step does is shrink the array furthermore if it is possible to 'remove' any negatives in a smart way
///i also make it reiterate for as long as there is no more shrinking available, because if you think about it not always
///can the pc know if, after a shrinking has occured, there are more shrinkings to be done
///then, lastly, it will calculate which of the positive numbers left is highest, and it will choose that as remaining maximum sum :)
///expected result for the array of input, s[], would be (i think), 7
int main() {
const int n=4;
int s[n+1]={3,-2,4,-4,6};
int k[n+1]={0};
///PRINT ARRAY, FOR DEBUG
std::cout<<" ( ";
for (int i = 0; i <= n; i++) { std::cout<<k[i]<<" "; }
std::cout<<")"<<std::endl;
int i=0, j=0;
// step 1: compress negative and postive subsegments of array s[] into single numbers within array k[]
/*while (i<=n)
{
while (s[i]>=0)
{
k[j]+=s[i]; ++i;
}
++j;
while (s[i]<0)
{
k[j]+=s[i]; ++i;
}
++j;
}*/
while (i<=n)
{
while (s[i]>=0)
{
if (i>n) break;
k[j]+=s[i]; ++i;
}
++j;
while (s[i]<0)
{
if (i>n) break;
k[j]+=s[i]; ++i;
}
++j;
}
std::cout<<"STEP 1 : ";
///PRINT ARRAY, FOR DEBUG
std::cout<<" ( ";
for (int i = 0; i <= n; i++) { std::cout<<k[i]<<" "; }
std::cout<<")"<<std::endl;
j=0;
// step 2: remove negative numbers when handy
std::cout<<"checked WRONG! "<<unsigned(k[3])<<std::endl;
int p=1;
while (p!=0)
{
p=0;
while (j<=n)
{
std::cout<<"checked right! "<<unsigned(k[j+1])<<std::endl;
if (k[j]<=0) { ++j; continue;}
if ( k[j]>unsigned(k[j+1]) && k[j+2]>unsigned(k[j+1]) )
{
std::cout<<"checked right!"<<std::endl;
k[j+2]=k[j]+k[j+1]+k[j+2];
k[j]=0; k[j+1]=0;
++p;
}
j+=2;
}
}
std::cout<<"STEP 2 : ";
///PRINT ARRAY, FOR DEBUG
std::cout<<" ( ";
for (int i = 0; i <= n; i++) { std::cout<<k[i]<<" "; }
std::cout<<")"<<std::endl;
j=0; i=0; //i will now use "i" and "p" variables for completely different purposes, as not to waste memory
// i will be final value that algorithm needed to find
// p will be a value to put within i if it is the biggest number found yet, it will keep changing as i go through the array....
// step 3: check which positive number is bigger: IT IS THE MAX ACHIEVABLE SUM!!
while (j<=n)
{
if(k[j]<=0) { ++j; continue; }
p=k[j]; if (p>i) { std::swap(p,i); }
j+=2;
}
std::cout<<std::endl<<"MAX ACHIEVABLE SUM WITHIN SUBSEGMENTS OF ARRAY : "<<i<<std::endl;
return 0;
}
might there be problems because im not using vectors??
Thanks for your help!
EDIT: i found both my algorithm bugs!
one is the one mentioned by user m24p, found in step 1 of the algorithm, which i fixed with a kinda-ugly get-around which ill get to cleaning up later...
the other is found in step2. it seems that in the while expression check, where i check something against unsigned values of the array, what is really checked is that something agains unsigned values of some weird numbers.
i tested it, with simple cout output:
IF i do unsigned(k[anyindexofk]) and the value contained in that spot is a positive number, i get the positive number of course which is unsigned
IF that number is negative though, the value won't be simply unsigned, but look very different, like i stepped over the array or something...i get this number "4294967292" when im instead expecting -2 to return as 2 or -4 to be 4.
(that number is for -4, -2 gives 4294967294)
I edited the sources with my new stuff, thanks for the help!
EDIT 2: nvm i resolved with std::abs() using cmath libs of c++
would there have been any other ways without using abs?
In your code, you have:
while (s[i]>=0)
{
k[j]+=s[i]; ++i;
}
Where s is initialized like so
int s[n+1]={3,-2,4,-4,6};
This is one obvious bug. Your while loop will overstep the array and hit garbage data that may or may not be zeroed out. Nothing stops i from being bigger than n+1. Clean up your code so that you don't overstep arrays, and then try debugging it. Also, your question is needs to be much more specific for me to feel comfortable answering your question, but fixing bugs like the one I pointed out should make it easier to stop running into inconsistent, undefined behavior and start focusing on your algorithm. I would love to answer the question but I just can't parse what you're specifically asking or what's going wrong.

C++ total beginner needs guidance [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
yesterday,we had to solve problems at the codeforces contest
I couldn't solve this problem since I am a total beginner.
http://codeforces.com/contest/353/problem/A
I used this algorithm, but something is wrong with it. I think it should print s or f, however it prints nothing. it just auto closes. Even when I added an input to stop instant close
#include <cstdlib>
#include <iostream>
using namespace std;
int main(){
int y=0;
int x=0;
int f;
int a;
cin >> a;
int s;
s = 0;
int number [a][a];
for(int i = 0;i<a;i++){
cin >> number[i][0] >> number[i][1];
x += number[i][0];
y += number[i][1];
}
for(int i = 0;i<a;i++){
if(x%2==0 && y%2==0){
return s;
}else if(y%2!=0 && x%2==0){
f = -1;
return f;
}else if(y%2==0 && x%2!=0){
f = -1;
return f;
}else{
y+= number[i][0];
x+= number[i][1];
s++;
}
}
int g;
if(f!=-1){
cout << s;
}else{
cout << f;
}
}
As Angew said, the return statements are incorrect and causing you to exit your main. You want to replace this by a break; to exit the loop but not the function.
I have not spent effort in trying to understand your algorithm, but at first glance it looks more complicated than it should be.
From my understanding of the problem, there are 3 possibilities:
the totals of the upper halves and the lower halves are already even (so nothing needs to be done)
the totals of the upper halves and the lower halves cannot be made even (so no solution exists)
just one Domino needs to be rotated to get the totals of the upper halves and the lower halves to be even (so the time needed is 1 second)
I base this on the fact that adding only even numbers always gives an even result, and adding an even number of odd numbers also always gives an even result.
Based on this, instead of having a 2-dimensional array like in your code, I would maintain 2 distinct arrays - one for the upper half numbers and the other for the lower half numbers. In addition, I would write the following two helper functions:
oddNumCount - takes an array as input; simply returns the number of odd numbers in the array.
oddAndEvenTileExists - takes 2 arrays as input; returns the index of the first tile with an odd+even number combination, -1 if no such tile exists.
Then the meat of my algorithm would be:
if (((oddNumCount(upper_half_array) % 2) == 0) && ((oddNumCount(lower_half_array) % 2) == 0))
{
// nothing needs to be done
result = 0;
}
else if (((oddNumCount(upper_half_array) - oddNumCount(lower_half_array)) % 2) == 0)
{
// The difference between the number of odd numbers in the two halves is even, which means a solution may exist.
// A solution really exists only if there exists a tile in which one number is even and the other is odd.
result = (oddAndEvenTileExists(upper_half_array, lower_half_array) >= 0) ? 1 : -1;
}
else
{
// no solution exists.
result = -1;
}
If you wanted to point out exactly which tile needs to be rotated, then you can save the index that "oddAndEvenTileExists" function returns.
You can write the actual code yourself to test if this works. Even if it doesn't, you would have written some code that hopefully takes you a little above "total beginner".

dynamic programming: coin change

I have as an input:
the number of testcases
an amount of money
As output I need:
The number different coins we have and the value of each coin.
The program should determine whether there is a solution or not, so the output should be either a "yes" or a "no".
I wrote the program using dynamic programming, but it only works when I enter one testcase at a time If i write let's say 200 testcases at once, the output isn't always right.
I'm assuming that I have an issue with incorrectly saved state between test cases.
My question is, how could I solve this problem? I'm only asking for some advice.
Here's my code:
#include<iostream>
#include<stdio.h>
#include<string>
#define max_muenzwert 1000
using namespace std;
int coin[10];//max. 10 coins
int d[max_muenzwert][10];//max value of a coin und max. number of coins
int tabelle(int s,int k)//computes table
{
if(d[s][k]!=-1) return d[s][k];
d[s][k]=0;
for(int i=k;i<=9&&s>=coin[i];i++)
d[s][k]+=tabelle(s-coin[i],i);
return d[s][k];
}
int main()
{
int t;
for(cin>>t;t>0;t--)//number of testcases
{
int n; //value we are searching
scanf("%d",&n)==1;
int n1;
cin>>n1;//how many coins
for (int n2=0; n2<n1; n2++)
{
cin>>coin[n2];//value of coins
}
memset(d,-1,sizeof(d));//set table to -1
for(int i=0;i<=9;i++)
{
d[0][i]=1;//set only first row to 1
}
if(tabelle(n,0)>0) //if there's a solution
{
cout<<"yes"<<endl;
}
else //no solution
{
cout<<"no"<<endl;
}
}
//system("pause");
return 0;
}
As you can see you have variable number of coins, which you are taking input using this line: cin>>n1;//how many coins. But in the tabelle method you are always looping through 0 - 9, which is wrong. You should only loop through 0 - n1. Try this test case:
2
10
2
2 5
10
1
9
For the second test set your answer should be no but your program will say yes as it will find 5 in the second element of your coin array.
for(int i=k;i<=9&&s>=coin[i];i++)
d[s][k]+=tabelle(s-coin[i],i);
Here, if coin[i] < s, then the entire loop will break, while you only need to skip this coin.
P.S. Please bother yourself with proper code formatting.