why am i getting time limit exceed - c++

I was trying to solve this problem in leetcode.
problem: heap problem
this is my code:
class Solution {
public:
vector<string> findRelativeRanks(vector<int>& score) {
priority_queue<pair<int,int>,vector<pair<int,int>>>mxheap;
for(int i=0; i<score.size(); i++){
mxheap.push({score[i],i});
}
vector<string>ans(score.size());
int place = 1;
while(!mxheap.empty()){
switch(place){
case 1:
ans[mxheap.top().second] = "Gold Medal";
mxheap.pop();
break;
case 2:
ans[mxheap.top().second] = "Silver Medal";
mxheap.pop();
break;
case 3:
ans[mxheap.top().second] = "Bronze Medal";
mxheap.pop();
break;
default:
ans[mxheap.top().second] = to_string(place);
}
place++;
}
return ans;
}
};
I don't know why I am getting the time limit exceeds I also tried removing the pair and using a map but that also didn't work.
I also saw some answers in discuss section those answers were also of (nlogn) time complexity but they worked fine mine is also (nlogn) still its not working can someone please tell me what am I doing wrong here.

Because you are not popping off the element in the default case.
ans[mxheap.top().second] = to_string(place);
mxheap.pop(); // Add this
which leads to an infinite while loop since your queue never becomes empty and hence the TLE.
You should be using a debugger to root-cause these problems and add breakpoints in your program to verify the expected program state at those points.

Related

SCIPgetSolVal from SCIP solver is not returning the solution values

I have been using SCIP for some time and have never had problems with these functions. However, I recently ran several input scenarios to pull different results from scip.
There was a case where the SCIPgetSolVal function did not work as it should.
If I do SCIPprintBestSol (scipProblem, NULL, TRUE) it shows me the results and they are within limits. When I next get the results with the SCIPgetSolVal function it returns me values of magnitude "1E + 99".
Note that it always works, except for some cases, I think the most logical thing is to be a problem with the input data, but I think in that case SCIPprintBestSol would not have viable results.
It seems to me like a memory allocation problem but I don't understand why it happens and how I can fix it.
I don't know if it's relevant but it's in c ++ on windows.
SCIPsolve(scipProblem);
SCIPprintBestSol(scipProblem, NULL, TRUE); //VALID RESULTS
/* SCIP Problem Results */
SCIP_Status status = SCIPgetStatus(scipProblem);
if(status == SCIP_STATUS_INFEASIBLE)
{
result = false;
}
else
{
for(int t=0; t<100; t++)
{
result(t,0) = SCIPgetSolVal(scipProblem, sol, probVars.at(t));
cout<< "Solution :"<< result(t,0) << endl;//WRONG RESULTS
}
}

C++ Beginner - While loop repeating first iteration [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
All,
So I've been really racking my brain about this one. I have a section of my program that needs to count spaces/vowels/characters in a user-specified string. This is one of those "teach you the way no one would do it because you can only used what we've covered in class already" kinds of assignments. So I have the user input a text, ending with a sentinel char, which in this case is '#'. The loop works wonderfully in regards to exiting when the sentinel is encountered, but it keeps iterating twice over string[0]. Here's the code:
i = 0;
characterToBeProcessed = userInputText.at(i);
while (characterToBeProcessed != LOOP_SENTINEL)
{
fout << characterToBeProcessed;
// Convert to lowercase
characterToBeProcessed =
static_cast<char> (tolower(characterToBeProcessed));
// Increment character counters
switch (characterToBeProcessed)
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
totalVowelCount++;
totalCharacterCount++;
break;
case ' ':
totalSpaceCount++;
totalCharacterCount++;
break;
default:
totalCharacterCount++;
break;
}
characterToBeProcessed = userInputText.at(i++);
}
So when I input at the prompt:
"Please input a text to be analyzed, ending with the # character: "
Hi there, my friend!#
The output is:
Below is the text entered by the user:
HHi there, my friend!
Total characters: 21
Total vowels: 5
Total blank spaces: 3
I've had the program output the chars for .at(0) and .at(1), and those give me the correct characters, I just can't figure out why the loop iterates twice for the first char and then works fine after that second time through. The counts/output are otherwise correct except for the first char being duplicated. Any appreciation would be greatly appreciated.
As others have said, the right way to solve problems of this kind is to use a debugger. It would save you lots and lots of time.
But in any case, your error is that at the end of your while loop, you do this:
characterToBeProcessed = userInputText.at(i++);
But before your while loop, you do this:
characterToBeProcessed = userInputText.at(i);
Your problem is that you are not incrementing i each time you use it, which naturally results in the observed behavior.
A character at the first position is read twice
i = 0;
characterToBeProcessed = userInputText.at(i);
^^^^^^
while (characterToBeProcessed != LOOP_SENTINEL)
{
//...
characterToBeProcessed = userInputText.at(i++);
^^^^^^^^
}
If you need to use the while loop then it can look like
i = 0;
while ( ( characterToBeProcessed = userInputText.at( i++) ) != LOOP_SENTINEL )
{
//...
// remove the next statement
// characterToBeProcessed = userInputText.at(i++);
}
Also this statement
totalCharacterCount++;
is used under each label. It is better to place it outside the switch statement either before it or after it. For example
totalCharacterCount++;
switch (characterToBeProcessed)
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
totalVowelCount++;
break;
case ' ':
totalSpaceCount++;
break;
default:
break;
}

LeetCode Word Break, fail on Online Judge but pass Online test

I met a problem when I was doing leetcode 139, word break.
Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words. (each dictionary word can be used multiple times.)
For example, given
s = "leetcode",
dict = ["leet", "code"].
Return true because "leetcode" can be segmented as "leet code".
I use basic dynamic programming algorithm, but may implement it in a different way from the popular one on the internet.
Here is the code:
class Solution {
public:
bool wordBreak(string s, unordered_set<string>& wordDict) {
int strlen = s.length();
if(0 == strlen) return true;
vector<bool> sepable(false, strlen);
for(int i = 0; i < strlen; ++i) {
if(wordDict.count(s.substr(0,i+1)) > 0) {
sepable[i] = true;
continue;
}
for(int j = 0; j < i; ++j) {
if(sepable[j] && wordDict.count(s.substr(j+1,i-j)) > 0) {
sepable[i] = true;
break;
}
}
}
return sepable[strlen-1];
}
};
When I ran online judge, it fails at the test:" "aaaaaaa" ["aaaa","aa"]", my code output true, the expected answer is false. However, if I run it on online test, it gives the right output. Also, it works fine on my own virtual machine with clang++.
The difference between online judge and online test is that each online test is only one test. Online judge contains many tests and will fail if anyone of the tests fails. So the problem of my code may lay like this: at some test other than the "aaaaaaa", it gives the right output but cause some potential problem. And that is why my code will fail on "aaaaaaa". However, if I just run this single test, it is fine.
The leetcode website says it may because my code has some undefined behaviors. The previous test case may influence the latter one. I don't know what are all the previous test case and didn't expect anyone here know about it. But I think as long as there are problems in my code, someone can find it.
I think the question is pretty clear this time.
this line parameters are of wrong order vector<bool> sepable(false, strlen); it should be vector<bool> sepable(strlen,false);the length of the vector comes first then the default value and false is implicitly converted to int so the length is set to 0 that gave the undefined behavior

Using a switch in a do..while loop, in C++

A simple programm that reads strings, and responds using a switch;
in this do-while loop containing a switch, I am able to run case 1-4 with no issues, but once i hit the default case, the programme simply loops the default case over and over again the code is as follows;
do { switch ( switchstring (entry, input) )
/*the switchstring function is one 1 wrote to convert a given entry(string),
into an input(integer)*/
{
case 1:
//code
repeat = 2;
break;
case 2:
//code
repeat = 2;
break;
case 3:
//code
repeat = 2;
break;
case 4:
//code
repeat = 2;
break;
default:
//code
repeat = 1;
break;}} while(repeat == 1);
the 2nd question is regarding my switchstring() function; is there a way to change the switch function such that it reads;
case (insert string):
i.e. so that I can remove the entire switchstring() function
thanks in advance!
Show us how switchstring (entry, input) works.
The problem you are facing is because, in default you do the following:
repeat = 1;
Which makes while(repeat == 1) always true. And then switchstring (entry, input) always return something that makes your switch block always go the the default case again.
When no case will be true in switch, then it will go in default case of switch and you are specifying repeat=1; in default. After that while condition will be checked and it will be true because repeat is 1, again it will go to do and check condition, your switch function will return something and it will go to default.
To solve 2nd question regarding your switchstring() function, you have to show your code what you are doing in that function, So that i can give you best suggestion.

Calling a class function from a Vector instead of an Array

I am currently working on a way to load a bunch of different NPCs from a file and loading it into my game. I have everything working correctly with arrays but I would like to change it to using a vector since I can change the size in case I need more NPCs than the space available in the array and so I don't just have a mostly empty array if I dont need many NPCs at the current time. Note that the following code is from a testing program, not my actual programming. I made it so I dont mess with the complete project by accident.
int main()
{
char input;
bool Running = true;
NPC Creatures[MAX_NPCS];
//InitCreatures loads the X, Y and Type from the file. I know with vectors I have to
//resize it as I go along, Which would be included in the function.
if(Creatures[MAX_NPCS].InitCreatures(Creatures) == false)
{
Creatures[MAX_NPCS].CleanUp(Creatures);
return 0;
}
while(Running == true)
{
cout << "(C)heck an NPC, (A)ttack and NPC or (E)xit the program\n";
cin >> input;
switch(input)
{
case 'C': Creatures[MAX_NPCS].Check(Creatures); break;
case 'c': Creatures[MAX_NPCS].Check(Creatures); break;
//The Check function just shows the X, Y and Type of the NPC
case 'A': Creatures[MAX_NPCS].Attack(Creatures); break;
case 'a': Creatures[MAX_NPCS].Attack(Creatures); break;
//Attack shows X, Y and type and then removes that NPC from the array.
case 'E': Running = false; break;
case 'e': Running = false; break;
default: cout << "That was not a valid input\n"; break;
}
}
Creatures[MAX_NPCS].CleanUp(Creatures);
cout << "Exiting\n";
system("PAUSE");
return 0;
}
Really the only problem I am having is getting Main to run the NPC Class functions from a vector instead of using the Array like I have now. I can easily change the other things in the functions I'm calling to accept the vector and handle it correctly.
When trying to use a vector to run the functions I was only able to call them when I had something like this:
Creatures[1].Attack(Creatures);
Of course when I call them like that the values don't return correctly and I usually get an error and Besides I don't know how many NPCs will be loaded for the current map, if Any.
Any help with this would be appreciated. I realize I am a newbie when it comes to programming, especially when it comes to Vectors. If my function code is needed I will gladly post it.
You could just create a vector and have the first element in there to be able to call the InitCreatures function (you could also overwrite the first creature later).
vector<NPC> Creatures(1);
Creatures[0].InitCreatures(Creatures);
I'm assuming that in class you have the parameter passed by reference.
bool InitCreatures(vector<NPC>& x) { ... }
But since you give creatures as a parameter to every function you have (do you need it in check or attack?) - wouldn't it be better to have a class to hold the NPC vector?