There are N number of cities. Each city has a teleport of type 1 to 10(inclusive). You are given an array of size N representing each city's teleport type by integer. For ex. 1 3 5 3 8 9
. The goal is to find the minimum amount of hours it takes to get from the first entry in the array to the last given the following rules:
- From each city (entry in the array) you can move to it's left or right neighbor (if it has one) and that action costs 1 hour.
- From each city you can teleport to another one with the same type of teleport as the one you're teleporting from. In the example array above you could teleport from the city at index 1 to city at index 3 because they both have the same type of teleport:
3
. This action costs a given number R of hours.
I have implemented a dynamic programming solution that works perfectly fine when the fastest way is only moving forward. But for some cases, it's quicker to go back few cities to then teleport forward, thus minimizing the amount of hours spent.
This is an example of when my algorithm fails: ex. 2 1 3 4 6 8 5 7 4 2 3 5 2 1 3 4 3 5 6 7
and R = 2
Correct answer: index 0 (time = 0) -> index 9 (time = 2) -> index 8 (time = 3) -> index 7 (time = 4) -> index 19 (time = 6).
My algorithm would find the quickest way only moving forwards, when clearly, the correct quickest way also involves moving backwards.
Here's my code so far:
#include <iostream>
using namespace std;
int main()
{
int dp[200] = {};
short ti[200] = {};
int numCities, R;
cin >> numCities >> R;
for (int i = 0; i < numCities; i++)
{
short temp;
cin >> temp;
ti[i] = temp;
}
for (int i = 1; i < numCities; i++)
{
dp[i] = dp[i - 1] + 1;
for (int x = i - 1; x >= 0; x--)
{
if (ti[x] == ti[i])
{
if (R + dp[x] < dp[i])
dp[i] = R + dp[x];
}
}
}
cout << dp[numCities - 1];
return 0;
}
How do I make my algorithm work for these kind of cases, where a lower state depends on a greater one?
EDIT: I use dynamic programming the following way: For each of the cities, I compute the quickest way to get to them given the starting state dp[0] = 0
.
Then the recurrence relation is: dp[i] = min(dp[i - 1] + 1, dp[every other point with same teleport type] + R)