Why this code is giving segmentation fault? - c++14

Alice is playing an arcade game and wants to climb to the top of the leaderboard and wants to track her ranking. Its leaderboard works like this:
-The player with the highest score is ranked number on the leaderboard.
-Players who have equal scores receive the same ranking number, and the next player(s) receive the immediately following ranking number.
For example, the four players on the leaderboard have high scores of 100, 90, 90 and 80. Those players will have ranks 1, 2, 2 and 3 respectively. If Alice's scores are 70, 80 and 105 her rankings after each game are 4th, 3rd and 1st.
#include <bits/stdc++.h>
using namespace std;
struct table{
int rank;
int score;
};
This is a modified binary search function iplementation for searching the score.
int search(vector<table> v,int low,int high,int n,int x){
if(low<=high){
int mid =(high+low)/2;
if((v[mid].score==x) || (mid==0 && v[mid].score<x))
return v[mid].rank;
if(mid==n-1 && v[mid].score>x)
return (v[mid].rank + 1);
if(v[mid].score>x && x>v[mid+1].score && mid<n-1)
return v[mid+1].rank;
if(v[mid].score>x)
return search(v,mid+1,high,n,x);
else
return search(v,low,mid-1,n,x);
}
return -1;
}
Main climbingLeaderboard function
vector<int> climbingLeaderboard(vector<int> scores, vector<int> alice) {
vector<table> v;
vector<int> res;
int n = scores.size();
int m = alice.size();
int x=1;
for(int i=0 ; i<n ; i++){
if(scores[i]!=scores[i-1] && i>0)
x++;
v[i].rank = x;
v[i].score = scores[i];
}
int z;
for(int i=0 ; i<m ; i++){
x=alice[i];
z = search(v,0,n-1,n,x);
res.push_back(z);
}
return res;
}
Driver Program
int main(){
int scores_count;
cin >> scores_count;
vector<int> scores; `//vector for storing leaderboard scores`
int k;
for(int i=0 ; i<scores_count ; i++){
cin >> k;
scores.push_back(k);
}
int game_count; `//number of games played by alice`
vector<int> Alice; `//vector for storing Alice's scores`
for(int i=0 ; i<game_count ; i++){
cin >> k;
alice.push_back(k);
}
vector<int> result; `//vector for storing result rank of each game of Alice`
result = climbingLeaderboard(scores,alice);
for(auto i = result.begin() ; i!=result.end() ; i++){
cout << *i << endl;
}
return 0;
}

Problem: In your climbingLeaderboard function, the first loop will attempt to access scores[i-1] when i is set to 0, resulting in a negative index for a std::vector access.
Fix: Change the for loop to start from i=1.
Problem 2: You access v by index without instantiating any structures to hold the data (e.g. v[i].rank = x).
Fix 2: Create an instance of the structure and write the data to it, then push it back into the vector v. Alternatively, reserve the memory for the whole vector as a preallocation.
Problem 3: On closer inspection, your search functionality is definitely broken. You should probably test this in isolation from the rest of the code.

Core Dump/Segmentation fault is a specific kind of error caused by accessing memory that does not belong to you.
Error in function:Main climbingLeaderboard function:
Accessing out of array index bounds
Start Loop From I =1 as you are doing score[i-1] which here in the first iteration would score[-1] (index) and there is no -1 index in c++
for(int i=1; i<n ; i++){
if(scores[i]!=scores[i-1] && i>0)
x++;
v[i].rank = x;
v[i].score = scores[i];
}

Related

Need to find highest non repeating number in custom vector

I'm creating a program, where you input n amount of mushroom pickers, they are in a shroom picking contest, they can find shroomA (worth 5 points), shroomB (worth 3 points) and shroomC (worth 15 points). I need to find the contest winner and print his/her name, but if two or more contestants have the same amount of points they are disqualified, meaning I need to find the highest non repeating result.
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class ShroomPicker {
private:
string name;
long long int shroomA, shroomB, shroomC;
public:
void Input() {
char Name[100];
long long int shrooma, shroomb, shroomc;
cin >> Name >> shrooma >> shroomb >> shroomc;
name = Name;
shroomA = shrooma; shroomB = shroomb; shroomC = shroomc;
}
long long int calcPoints() {
return shroomA * 5 + shroomB * 3 + shroomC * 15;
}
string winnersName() {
return name;
}
};
int main() {
int n;
cin >> n;
vector<ShroomPicker> shr;
for (int i = 0; i < n; i++) {
ShroomPicker s;
s.Input();
shr.push_back(s);
}
long long int hiscore = 0;
int num = 0;
for (int i = 0; i < n; i++) {
long long int temp = 0;
temp = shr[i].calcPoints();
if (temp > hiscore) {
hiscore = temp;
num = i;
}
}
cout << shr[num].winnersName();
}
I made this program which finds the highest score even if repeats more than once, could someone suggest how I can find the highest non repeating score?
edit:
for (int i = 0; i < n; i++) {
long long int temp = 0;
temp = shr[i].calcPoints();
if (scoreMap.find(temp) == scoreMap.end()) {
scoreMap[temp] = Info{ i, false };
}
else {
scoreMap[temp] = Info{ i, true };
}
}
I would suggest sorting the list of participants in decreasing number of mushrooms picked (O[nlogn]) and then look through the list from start to finish (O[n] max). The first participant whose number of mushrooms picked is different than those of the adjacent participants (in the sorted list) is the winner.
The fastest (O(N)) way I can think of is to have:
struct Info
{
int picker_index;
bool disqualified;
}
// map from score to the Info object above
std::unordered_map<int, Info> scoreMap;
Iterate through pickers and update the map as follows:
-- If no item in the map, just add scoreMap[score] = Info {picker_index, false};
-- else, set disqualified = true on the existing item;
Once the map is constructed, find the max key in the map for which disqualified = false; similar to what you are doing now.

Recursive algorithm to find all possible solutions in a nonogram row

I am trying to write a simple nonogram solver, in a kind of bruteforce way, but I am stuck on a relatively easy task. Let's say I have a row with clues [2,3] that has a length of 10
so the solutions are:
$$-$$$----
$$--$$$---
$$---$$$--
$$----$$$-
$$-----$$$
-$$----$$$
--$$---$$$
---$$--$$$
----$$-$$$
-$$---$$$-
--$$-$$$--
I want to find all the possible solutions for a row
I know that I have to consider each block separately, and each block will have an availible space of n-(sum of remaining blocks length + number of remaining blocks) but I do not know how to progress from here
Well, this question already have a good answer, so think of this one more as an advertisement of python's prowess.
def place(blocks,total):
if not blocks: return ["-"*total]
if blocks[0]>total: return []
starts = total-blocks[0] #starts = 2 means possible starting indexes are [0,1,2]
if len(blocks)==1: #this is special case
return [("-"*i+"$"*blocks[0]+"-"*(starts-i)) for i in range(starts+1)]
ans = []
for i in range(total-blocks[0]): #append current solutions
for sol in place(blocks[1:],starts-i-1): #with all possible other solutiona
ans.append("-"*i+"$"*blocks[0]+"-"+sol)
return ans
To test it:
for i in place([2,3,2],12):
print(i)
Which produces output like:
$$-$$$-$$---
$$-$$$--$$--
$$-$$$---$$-
$$-$$$----$$
$$--$$$-$$--
$$--$$$--$$-
$$--$$$---$$
$$---$$$-$$-
$$---$$$--$$
$$----$$$-$$
-$$-$$$-$$--
-$$-$$$--$$-
-$$-$$$---$$
-$$--$$$-$$-
-$$--$$$--$$
-$$---$$$-$$
--$$-$$$-$$-
--$$-$$$--$$
--$$--$$$-$$
---$$-$$$-$$
This is what i got:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
typedef std::vector<bool> tRow;
void printRow(tRow row){
for (bool i : row){
std::cout << ((i) ? '$' : '-');
}
std::cout << std::endl;
}
int requiredCells(const std::vector<int> nums){
int sum = 0;
for (int i : nums){
sum += (i + 1); // The number + the at-least-one-cell gap at is right
}
return (sum == 0) ? 0 : sum - 1; // The right-most number don't need any gap
}
bool appendRow(tRow init, const std::vector<int> pendingNums, unsigned int rowSize, std::vector<tRow> &comb){
if (pendingNums.size() <= 0){
comb.push_back(init);
return false;
}
int cellsRequired = requiredCells(pendingNums);
if (cellsRequired > rowSize){
return false; // There are no combinations
}
tRow prefix;
int gapSize = 0;
std::vector<int> pNumsAux = pendingNums;
pNumsAux.erase(pNumsAux.begin());
unsigned int space = rowSize;
while ((gapSize + cellsRequired) <= rowSize){
space = rowSize;
space -= gapSize;
prefix.clear();
prefix = init;
for (int i = 0; i < gapSize; ++i){
prefix.push_back(false);
}
for (int i = 0; i < pendingNums[0]; ++i){
prefix.push_back(true);
space--;
}
if (space > 0){
prefix.push_back(false);
space--;
}
appendRow(prefix, pNumsAux, space, comb);
++gapSize;
}
return true;
}
std::vector<tRow> getCombinations(const std::vector<int> row, unsigned int rowSize) {
std::vector<tRow> comb;
tRow init;
appendRow(init, row, rowSize, comb);
return comb;
}
int main(){
std::vector<int> row = { 2, 3 };
auto ret = getCombinations(row, 10);
for (tRow r : ret){
while (r.size() < 10)
r.push_back(false);
printRow(r);
}
return 0;
}
And my output is:
$$-$$$----
$$--$$$---
$$---$$$--
$$----$$$--
$$-----$$$
-$$-$$$----
-$$--$$$--
-$$---$$$-
-$$----$$$-
--$$-$$$--
--$$--$$$-
--$$---$$$
---$$-$$$-
---$$--$$$
----$$-$$$
For sure, this must be absolutely improvable.
Note: i did't test it more than already written case
Hope it works for you

Make unique array with minimal sum

It is a interview question. Given an array, e.g., [3,2,1,2,7], we want to make all elements in this array unique by incrementing duplicate elements and we require the sum of the refined array is minimal. For example the answer for [3,2,1,2,7] is [3,2,1,4,7] and its sum is 17. Any ideas?
It's not quite as simple as my earlier comment suggested, but it's not terrifically complicated.
First, sort the input array. If it matters to be able to recover the original order of the elements then record the permutation used for the sort.
Second, scan the sorted array from left to right (ie from low to high). If an element is less than or equal to the element to its left, set it to be one greater than that element.
Pseudocode
sar = sort(input_array)
for index = 2:size(sar) ! I count from 1
if sar(index)<=sar(index-1) sar(index) = sar(index-1)+1
forend
Is the sum of the result minimal ? I've convinced myself that it is through some head-scratching and trials but I haven't got a formal proof.
If you only need to find ONE of the best solution, here's the algorythm with some explainations.
The idea of this problem is to find an optimal solution, which can be found only by testing all existing solutions (well, they're infinite, let's stick with the reasonable ones).
I wrote a program in C, because I'm familiar with it, but you can port it to any language you want.
The program does this: it tries to increment one value to the max possible (I'll explain how to find it in the comments under the code sections), than if the solution is not found, decreases this value and goes on with the next one and so on.
It's an exponential algorythm, so it will be very slow on large values of duplicated data (yet, it assures you the best solution is found).
I tested this code with your example, and it worked; not sure if there's any bug left, but the code (in C) is this.
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
typedef int BOOL; //just to ease meanings of values
#define TRUE 1
#define FALSE 0
Just to ease comprehension, I did some typedefs. Don't worry.
typedef struct duplicate { //used to fasten the algorythm; it uses some more memory just to assure it's ok
int value;
BOOL duplicate;
} duplicate_t;
int maxInArrayExcept(int *array, int arraySize, int index); //find the max value in array except the value at the index given
//the result is the max value in the array, not counting th index
int *findDuplicateSum(int *array, int arraySize);
BOOL findDuplicateSum_R(duplicate_t *array, int arraySize, int *tempSolution, int *solution, int *totalSum, int currentSum); //resursive function used to find solution
BOOL check(int *array, int arraySize); //checks if there's any repeated value in the solution
These are all the functions we'll need. All split up for comprehension purpose.
First, we have a struct. This struct is used to avoid checking, for every iteration, if the value on a given index was originally duplicated. We don't want to modify any value not duplicated originally.
Then, we have a couple functions: first, we need to see the worst case scenario: every value after the duplicated ones is already occupied: then we need to increment the duplicated value up to the maximum value reached + 1.
Then, there are the main Function we'll discute later about.
The check Function only checks if there's any duplicated value in a temporary solution.
int main() { //testing purpose
int i;
int testArray[] = { 3,2,1,2,7 }; //test array
int nTestArraySize = 5; //test array size
int *solutionArray; //needed if you want to use the solution later
solutionArray = findDuplicateSum(testArray, nTestArraySize);
for (i = 0; i < nTestArraySize; ++i) {
printf("%d ", solutionArray[i]);
}
return 0;
}
This is the main Function: I used it to test everything.
int * findDuplicateSum(int * array, int arraySize)
{
int *solution = malloc(sizeof(int) * arraySize);
int *tempSolution = malloc(sizeof(int) * arraySize);
duplicate_t *duplicate = calloc(arraySize, sizeof(duplicate_t));
int i, j, currentSum = 0, totalSum = INT_MAX;
for (i = 0; i < arraySize; ++i) {
tempSolution[i] = solution[i] = duplicate[i].value = array[i];
currentSum += array[i];
for (j = 0; j < i; ++j) { //to find ALL the best solutions, we should also put the first found value as true; it's just a line more
//yet, it saves the algorythm half of the duplicated numbers (best/this case scenario)
if (array[j] == duplicate[i].value) {
duplicate[i].duplicate = TRUE;
}
}
}
if (findDuplicateSum_R(duplicate, arraySize, tempSolution, solution, &totalSum, currentSum));
else {
printf("No solution found\n");
}
free(tempSolution);
free(duplicate);
return solution;
}
This Function does a lot of things: first, it sets up the solution array, then it initializes both the solution values and the duplicate array, that is the one used to check for duplicated values at startup. Then, we find the current sum and we set the maximum available sum to the maximum integer possible.
Then, the recursive Function is called; this one gives us the info about having found the solution (that should be Always), then we return the solution as an array.
int findDuplicateSum_R(duplicate_t * array, int arraySize, int * tempSolution, int * solution, int * totalSum, int currentSum)
{
int i;
if (check(tempSolution, arraySize)) {
if (currentSum < *totalSum) { //optimal solution checking
for (i = 0; i < arraySize; ++i) {
solution[i] = tempSolution[i];
}
*totalSum = currentSum;
}
return TRUE; //just to ensure a solution is found
}
for (i = 0; i < arraySize; ++i) {
if (array[i].duplicate == TRUE) {
if (array[i].duplicate <= maxInArrayExcept(solution, arraySize, i)) { //worst case scenario, you need it to stop the recursion on that value
tempSolution[i]++;
return findDuplicateSum_R(array, arraySize, tempSolution, solution, totalSum, currentSum + 1);
tempSolution[i]--; //backtracking
}
}
}
return FALSE; //just in case the solution is not found, but we won't need it
}
This is the recursive Function. It first checks if the solution is ok and if it is the best one found until now. Then, if everything is correct, it updates the actual solution with the temporary values, and updates the optimal condition.
Then, we iterate on every repeated value (the if excludes other indexes) and we progress in the recursion until (if unlucky) we reach the worst case scenario: the check condition not satisfied above the maximum value.
Then we have to backtrack and continue with the iteration, that will go on with other values.
PS: an optimization is possible here, if we move the optimal condition from the check into the for: if the solution is already not optimal, we can't expect to find a better one just adding things.
The hard code has ended, and there are the supporting functions:
int maxInArrayExcept(int *array, int arraySize, int index) {
int i, max = 0;
for (i = 0; i < arraySize; ++i) {
if (i != index) {
if (array[i] > max) {
max = array[i];
}
}
}
return max;
}
BOOL check(int *array, int arraySize) {
int i, j;
for (i = 0; i < arraySize; ++i) {
for (j = 0; j < i; ++j) {
if (array[i] == array[j]) return FALSE;
}
}
return TRUE;
}
I hope this was useful.
Write if anything is unclear.
Well, I got the same question in one of my interviews.
Not sure if you still need it. But here's how I did it. And it worked well.
num_list1 = [2,8,3,6,3,5,3,5,9,4]
def UniqueMinSumArray(num_list):
max=min(num_list)
for i,V in enumerate(num_list):
while (num_list.count(num_list[i])>1):
if (max > num_list[i]+1) :
num_list[i] = max + 1
else:
num_list[i]+=1
max = num_list[i]
i+=1
return num_list
print (sum(UniqueMinSumArray(num_list1)))
You can try with your list of numbers and I am sure it will give you the correct unique minimum sum.
I got the same interview question too. But my answer is in JS in case anyone is interested.
For sure it can be improved to get rid of for loop.
function getMinimumUniqueSum(arr) {
// [1,1,2] => [1,2,3] = 6
// [1,2,2,3,3] = [1,2,3,4,5] = 15
if (arr.length > 1) {
var sortedArr = [...arr].sort((a, b) => a - b);
var current = sortedArr[0];
var res = [current];
for (var i = 1; i + 1 <= arr.length; i++) {
// check current equals to the rest array starting from index 1.
if (sortedArr[i] > current) {
res.push(sortedArr[i]);
current = sortedArr[i];
} else if (sortedArr[i] == current) {
current = sortedArr[i] + 1;
// sortedArr[i]++;
res.push(current);
} else {
current++;
res.push(current);
}
}
return res.reduce((a,b) => a + b, 0);
} else {
return 0;
}
}

Finding an efficient algorithm

You are developing a smartphone app. You have a list of potential
customers for your app. Each customer has a budget and will buy the app at
your declared price if and only if the price is less than or equal to the
customer's budget.
You want to fix a price so that the revenue you earn from the app is
maximized. Find this maximum possible revenue.
For instance, suppose you have 4 potential customers and their budgets are
30, 20, 53 and 14. In this case, the maximum revenue you can get is 60.
**Input format**
Line 1 : N, the total number of potential customers.
Lines 2 to N+1: Each line has the budget of a potential customer.
**Output format**
The output consists of a single integer, the maximum possible revenue you
can earn from selling your app.
Also, upper bound on N is 5*(10^5) and upper bound on each customer's budget is 10^8.
This is a problem I'm trying to solve . My strategy was to sort the list of budgets and then multiply each of those with its position-index in the sequence - and then print the max of the resulting sequence. However this seems to be quite time-inefficient (at least in the way I'm implementing it - I've attached the code for reference). My upper bound on time is 2 seconds. Can anyone help me find a
more time-efficient algorithm (or possibly a more efficient way to implement my algorithm) ?
Here is my solution :
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
using namespace std;
long long max(long long[],long long);
void quickSortIterative(long long[],long long,long long);
long long partition(long long[],long long,long long);
void swap(long long*,long long*);
int main(){
long long n,k=1;
scanf("%lld",&n);
if(n<1 || n > 5*((long long)pow(10,5))){
exit(0);
}
long long budget[n],aux[n];
for(long long i=0;i<n;i++){
scanf("%lld",&budget[i]);
if(budget[i]<1 || budget[i] > (long long)pow(10,8)){
exit(0);
}
}
quickSortIterative(budget,0,n-1);
for(long long j=n-1;j>=0;j--){
aux[j] = budget[j]*k;
k++;
}
cout<<max(aux,n);
return 0;
}
long long partition (long long arr[], long long l, long long h){
long long x = arr[h];
long long i = (l - 1);
for (long long j = l; j <= h- 1; j++)
{
if (arr[j] <= x)
{
i++;
swap (&arr[i], &arr[j]);
}
}
swap (&arr[i + 1], &arr[h]);
return (i + 1);
}
void swap ( long long* a, long long* b ){
long long t = *a;
*a = *b;
*b = t;
}
void quickSortIterative(long long arr[], long long l, long long h){
long long stack[ h - l + 1 ];
long long top = -1;
stack[ ++top ] = l;
stack[ ++top ] = h;
while ( top >= 0 ){
h = stack[ top-- ];
l = stack[ top-- ];
long long p = partition( arr, l, h );
if ( p-1 > l ){
stack[ ++top ] = l;
stack[ ++top ] = p - 1;
}
if ( p+1 < h ){
stack[ ++top ] = p + 1;
stack[ ++top ] = h;
}
}
}
long long max(long long arr[],long long length){
long long max = arr[0];
for(long long i=1;i<length;i++){
if(arr[i]>max){
max=arr[i];
}
}
return max;
}
Quicksort can take O(n^2) time for certain sequences (often already sorted sequences are bad).
I would recommend you try using a sorting approach with guaranteed O(nlogn) performance (e.g. heapsort or mergesort). Alternatively, you may well find that using the sort routines in the standard library will give better performance than your version.
You might use qsort in C or std::sort in C++, which is most likely faster than your own code.
Also, your "stack" array will cause you trouble if the difference h - l is large.
I have used STL library function sort() of C++. It's time complexity is O(nlogn). Here, you just need to sort the given array and check from maximum value to minimum value for given solution. It is O(n) after sorting.
My code which cleared all the test cases :
#include <algorithm>
#include <stdio.h>
#include <cmath>
#include <iostream>
using namespace std;
int main(){
long long n, a[1000000], max;
int i, j;
cin>>n;
for(i = 0; i < n; i++){
cin>>a[i];
}
sort(a, a + n);
max = a[n - 1];
for(i = n - 2; i >= 0; i--){
//printf("%lld ", a[i]);
if(max < (a[i] * (n - i)))
max = a[i] * (n - i);
}
cout<<max<<endl;
return 0;
}
I dont know if my answer is right or wrong please point out mistakes if there is any
#include<stdio.h>
void main()
{
register int i,j;
long long int n,revenue;
scanf("%Ld",&n);
long long int a[n];
for(i=0;i<n;i++)
scanf("%Ld",&a[i]);
for (i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
a[i]=a[i]+a[j];
a[j]=a[i]-a[j];
a[i]=a[i]-a[j];
}
}
}
for(i=0;i<n;i++)
a[i]=(n-i)*a[i];
revenue=0;
for(i=0;i<n;i++)
{
if(revenue<a[i])
revenue=a[i];
}
printf("%Ld\n",revenue);
}
passed all the test cases
n=int(input())
r=[]
for _ in range(n):
m=int(input())
r.append(m)
m=[]
r.sort()
l=len(r)
for i in range(l):
m.append((l-i)*r[i])
print(max(m))
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main() {
// your code goes here
long long n;
std::cin >> n;
long long a[n];
for(long long i=0;i<n;i++)
{
std::cin >> a[i];
}
sort(a,a+n);
long long max=LONG_MIN,count;
for(long long i=0;i<n;i++)
{
if(a[i]*(n-i)>max)
{
max=a[i]*(n-i);
}
}
std::cout << max << std::endl;
return 0;
}
The following solution is in C programming Language.
The Approach is:
Input the number of customers.
Input the budgets of customers.
Sort the budget.
Assign revenue=0
Iterate through the budget and Multiply the particular budget with the remaining budget values.
If the previous-revenue < new-revenue. assign the new-revenue to revenue variable.
The code is as follows:
#include <stdio.h>
int main(void) {
int i,j,noOfCustomer;
scanf("%d",&noOfCustomer);
long long int budgetOfCustomer[noOfCustomer],maximumRevenue=0;
for(i=0;i<noOfCustomer;i++)
{
scanf("%Ld",&budgetOfCustomer[i]);
}
for(i=0;i<noOfCustomer;i++)
{
for(j=i+1;j<noOfCustomer;j++)
{
if(budgetOfCustomer[i]>budgetOfCustomer[j])
{
budgetOfCustomer[i]=budgetOfCustomer[i] + budgetOfCustomer[j];
budgetOfCustomer[j]=budgetOfCustomer[i] - budgetOfCustomer[j];
budgetOfCustomer[i]=budgetOfCustomer[i] - budgetOfCustomer[j];
}
}
}
for(i=0;i<noOfCustomer;i++)
{
budgetOfCustomer[i]=budgetOfCustomer[i]*(noOfCustomer-i);
}
for(i=0;i<noOfCustomer;i++)
{
if(maximumRevenue<budgetOfCustomer[i])
maximumRevenue=budgetOfCustomer[i];
}
printf("%Ld\n",maximumRevenue);
return 0;
}

Contest Challenge: "Maximize number of races one can take part in"

While practising problems from hackerearth I came across following problem( not from active contest ) and have been unsuccessful in solving it after many attempts.
Chandler is participating in a race competition involving N track
races. He wants to run his old car on these tracks having F amount of
initial fuel. At the end of each race, Chandler spends si fuel and
gains some money using which he adds ei amount of fuel to his car.
Also for participating in race i at any stage, Chandler should have
more than si amount of fuel. Also he can participate in race i once.
Help Chandler in maximizing the number of races he can take part in if
he has a choice to participate in the given races in any order.
How can I approach the problem. My approach was to sort by (ei-si) but than I couldn't incorporate condition that fuel present is greater than required for race.
EDIT I tried to solve using following algorithm but it fails,I also can't think of any inputs which fail the algorithm. Please help me out figuring whats wrong or give some input where my algorithm fails.
Sort (ei-si) in non-increasing order;
start iterating through sorted (ei-si) and find first element such that fuel>=si
update fuel=fuel+(ei-si);
update count;
erase that element from list, and start searching again;
if fuel was not updated than we can't take part in any races so stop searching
and output count.
EDIT And here is my code as requested.
#include<iostream>
#include<vector>
#include<algorithm>
#include<list>
using namespace std;
struct race{
int ei;
int si;
int earn;
};
bool compareByEarn(const race &a, const race &b)
{
return a.earn <= b.earn;
}
int main(){
int t;
cin>>t;
while(t--){
vector<struct race> fuel;
int f,n;
cin>>f>>n;
int si,ei;
while(n--){
cin>>si>>ei;
fuel.push_back({ei,si,ei-si});
}
sort(fuel.begin(),fuel.end(),compareByEarn);
list<struct race> temp;
std::copy( fuel.rbegin(), fuel.rend(), std::back_inserter(temp ) );
int count=0;
while(1){
int flag=0;
for (list<struct race>::iterator ci = temp.begin(); ci != temp.end(); ++ci){
if(ci->si<=f){
f+=ci->earn;
ci=temp.erase(ci);
++count;
flag=1;
break;
}
}
if(!flag){
break;
}
}
cout<<count<<endl;
}
}
EDIT As noted in answer below, the above greedy approach dosen't always work. So now any alternative method would be useful
Here is my solution, which gets accepted by the judge:
Eliminate those races which have a profit (ei>si)
Sort by ei (in decreasing order)
Solve the problem using a dynamic programming algorithm. (It is similar to a pseudo-polynomial solution for the 0-1 knapsack.)
It is clear that the order in which you eliminate profitable races does not matter. (As long as you process them until no more profitable races can be entered.)
For the rest, I will first prove that if a solution exists, you can perform the same set of races in decreasing order of ei, and the solution will still be feasible. Imagine we have a solution in which k races were chosen and let's say these k races have starting and ending fuel values of s1,...,sk and e1,...,ek. Let i be the first index where ei < ej (where j=i+1). We will show that we can swap i and i+1 without violating any constraints.
It is clear that swapping i and i+1 will not disrupt any constraints before i or after i+1, so we only need to prove that we can still perform race i if we swap its order with race i+1 (j). In the normal order, if the fuel level before we start on race i was f, after race i it will be f-si+ei, and this is at least sj. In other words, we have: f-si+ei>=sj, which means f-sj+ei>=si. However, we know that ei < ej so f-sj+ej >= f-sj+ei >= si, and therefore racing on the jth race before the ith race will still leave at least si fuel for race i.
From there, we implement a dynamic programming algorithm in which d[i][j] is the maximum number of races we can participate in if we can only use races i..n and we start with j units of fuel.
Here is my code:
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
const int maxn = 110;
const int maxf = 110*1000;
int d[maxn][maxf];
struct Race {
int s, e;
bool used;
inline bool operator < (const Race &o) const {
return e > o.e;
}
} race[maxn];
int main() {
int t;
for (cin >> t; t--;) {
memset(d, 0, sizeof d);
int f, n;
cin >> f >> n;
for (int i = 0; i < n; i++) {
cin >> race[i].s >> race[i].e;
race[i].used = false;
}
sort(race, race + n);
int count = 0;
bool found;
do {
found = 0;
for (int i = 0; i < n; i++)
if (!race[i].used && race[i].e >= race[i].s && race[i].s >= f) {
race[i].used = true;
count++;
f += race[i].s - race[i].e;
found = true;
}
} while (found);
for (int i = n - 1; i >= 0; i--) {
for (int j = 0; j < maxf; j++) {
d[i][j] = d[i + 1][j];
if (!race[i].used && j >= race[i].s) {
int f2 = j - race[i].s + race[i].e;
if (f2 < maxf)
d[i][j] = max(d[i][j], 1 + d[i + 1][f2]);
}
}
}
cout << d[0][f] + count << endl;
}
return 0;
}
You need to change your compareByEarn function
bool compareByEarn(const race &a, const race &b)
{
if(a.earn == b.earn) return a.si < b.si;
return a.earn < b.earn;
}
Above comparison means, choose the track with more earning (or lesser loss). But if there are 2 tracks with same earning, prefer the track which requires more fuel.
Consider the example
Initially fuel in the car = 4
track 1 : s = 2, e = 1
track 2 : s = 3, e = 2
track 3 : s = 4, e = 3
Expected answer = 3
Received answer = 2 or 3 depending on whether sorting algorithm is stable or unstable and the order of input\.
As a side note:
Also for participating in race i at any stage, Chandler should have
more than si amount of fuel
Should translate to
if(ci->si < f){ // and not if(ci->si<=f){
You can check if my observation is right or problem author chose incorrect sentence to describe the constraint.
EDIT With more reasoning I realized you can not do it with only greedy approach.
Consider the following input.
Initially fuel in the car = 9
track 1 : s = 9, e = 6
track 2 : s = 2, e = 0
track 3 : s = 2, e = 0
track 4 : s = 2, e = 0
Expected answer = 4
Received answer = 3

Resources