Google Foobar, maximum unique visits under a resource limit, negative weights in graph

5k views Asked by At

I'm having trouble figuring out the type of problem this is. I'm still a student and haven't taken a graph theory/linear optimization class yet.

The only thing I know for sure is to check for negative cycles, as this means you can rack the resource limit up to infinity, allowing for you to pick up each rabbit. I don't know the "reason" to pick the next path. I also don't know when to terminate, as you could keep using all of the edges and make the resource limit drop below 0 forever, but never escape.

I'm not really looking for code (as this is a coding challenge), only the type of problem this is (Ex: Max Flow, Longest Path, Shortest Path, etc.) If you an algorithm that fits this already that would be extra awesome. Thanks.

The time it takes to move from your starting point to all of the bunnies and to the bulkhead will be given to you in a square matrix of integers. Each row will tell you the time it takes to get to the start, first bunny, second bunny, ..., last bunny, and the bulkhead in that order. The order of the rows follows the same pattern (start, each bunny, bulkhead). The bunnies can jump into your arms, so picking them up is instantaneous, and arriving at the bulkhead at the same time as it seals still allows for a successful, if dramatic, escape. (Don't worry, any bunnies you don't pick up will be able to escape with you since they no longer have to carry the ones you did pick up.) You can revisit different spots if you wish, and moving to the bulkhead doesn't mean you have to immediately leave - you can move to and from the bulkhead to pick up additional bunnies if time permits.

In addition to spending time traveling between bunnies, some paths interact with the space station's security checkpoints and add time back to the clock. Adding time to the clock will delay the closing of the bulkhead doors, and if the time goes back up to 0 or a positive number after the doors have already closed, it triggers the bulkhead to reopen. Therefore, it might be possible to walk in a circle and keep gaining time: that is, each time a path is traversed, the same amount of time is used or added.

Write a function of the form answer(times, time_limit) to calculate the most bunnies you can pick up and which bunnies they are, while still escaping through the bulkhead before the doors close for good. If there are multiple sets of bunnies of the same size, return the set of bunnies with the lowest prisoner IDs (as indexes) in sorted order. The bunnies are represented as a sorted list by prisoner ID, with the first bunny being 0. There are at most 5 bunnies, and time_limit is a non-negative integer that is at most 999.

2

There are 2 answers

1
David Eisenstat On

It's a planning problem, basically. The generic approach to planning is to identify the possible states of the world, the initial state, transitions between states, and the final states. Then search the graph that this data imply, most simply using breadth-first search.

For this problem, the relevant state is (1) how much time is left (2) which rabbits we've picked up (3) where we are right now. This means 1,000 clock settings (I'll talk about added time in a minute) times 2^5 = 32 subsets of bunnies times 7 positions = 224,000 possible states, which is a lot for a human but not a computer.

We can deal with added time by swiping a trick from Johnson's algorithm. As Tymur suggests in a comment, run Bellman--Ford and either find a negative cycle (in which case all rabbits can be saved by running around the negative cycle enough times first) or potentials that, when applied, make all times nonnegative. Don't forget to adjust the starting time by the difference in potential between the starting position and the bulkhead.

0
Tuhin Mukherjee On

There you go. I started Google Foobar yesterday. I'll be starting Level 5 shortly. This was my 2nd problem here at level 4. The solution is fast enough as I tried memoizing the states without using the utils class. Anyway, loved the experience. This was by far the best problem solved by me since I got to use Floyd-Warshall(to find the negative cycle if it exists), Bellman-Ford(as a utility function to the weight readjustment step used popularly in algorithms like Johnson's and Suurballe's), Johnson(weight readjustment!), DFS(for recursing over steps) and even memoization using a self-designed hashing function :) Happy Coding!!

public class Solution
{

public static final int INF = 100000000;
public static final int MEMO_SIZE = 10000;
public static int[] lookup;
public static int[] lookup_for_bunnies;

public static int getHashValue(int[] state, int loc)
{
    int hashval = 0;
    for(int i = 0; i < state.length; i++)
        hashval += state[i] * (1 << i);
    hashval += (1 << loc) * 100;

    return hashval % MEMO_SIZE;
}

public static boolean findNegativeCycle(int[][] times)
{
    int i, j, k;
    int checkSum = 0;
    int V = times.length;
    
    int[][] graph = new int[V][V];
    for(i = 0; i < V; i++)
        for(j = 0; j < V; j++)
        {
            graph[i][j] = times[i][j];
            checkSum += times[i][j];
        }
    if(checkSum == 0)
        return true;
        
    for(k = 0; k < V; k++)
        for(i = 0; i < V; i++)
            for(j = 0; j < V; j++)
                if(graph[i][j] > graph[i][k] + graph[k][j])
                    graph[i][j] = graph[i][k] + graph[k][j];
                
    for(i = 0; i < V; i++)
        if(graph[i][i] < 0)
            return true;
    return false;
}
    
public static void dfs(int[][] times, int[] state, int loc, int tm, int[] res)
{
    int V = times.length;
    if(loc == V - 1)
    {
        int rescued = countArr(state);
        int maxRescued = countArr(res);
        
        if(maxRescued < rescued)
            for(int i = 0; i < V; i++)
                res[i] = state[i];
        
        if(rescued == V - 2)
          return;
    }
    else if(loc > 0)
      state[loc] = 1;
    
    int hashval = getHashValue(state, loc);
    if(tm < lookup[hashval])
        return;
    else if(tm == lookup[hashval] && countArr(state) <= lookup_for_bunnies[loc])
        return;
    else
    {
        lookup_for_bunnies[loc] = countArr(state);
        lookup[hashval] = tm;
        for(int i = 0; i < V; i++)
        {
            if(i != loc && (tm - times[loc][i]) >= 0)
            {
                boolean stateCache = state[i] == 1;
                dfs(times, state, i, tm - times[loc][i], res);
                if(stateCache)
                    state[i] = 1;
                else
                    state[i] = 0;
            }
        }
    }
}

public static int countArr(int[] arr)
{
    int counter = 0;
    for(int i = 0; i < arr.length; i++)
      if(arr[i] == 1)
        counter++;
    return counter;
}

public static int bellmanFord(int[][] adj, int times_limit)
{
    int V = adj.length;
    int i, j, k;
    int[][] graph = new int[V + 1][V + 1];
    
    for(i = 1; i <= V; i++)
      graph[i][0] = INF;
      
    for(i = 0; i < V; i++)
      for(j = 0; j < V; j++)
        graph[i + 1][j + 1] = adj[i][j];
    
    int[] distance = new int[V + 1] ;
    for(i = 1; i <= V; i++)
      distance[i] = INF;
      
    for(i = 1; i <= V; i++)
      for(j = 0; j <= V; j++)
      {
        int minDist = INF;
        for(k = 0; k <= V; k++)
          if(graph[k][j] != INF)
            minDist = Math.min(minDist, distance[k] + graph[k][j]);
        distance[j] = Math.min(distance[j], minDist);
      }

    for(i = 0; i < V; i++)
      for(j = 0; j < V; j++)
        adj[i][j] += distance[i + 1] - distance[j + 1];

    return times_limit + distance[1] - distance[V];
}

public static int[] solution(int[][] times, int times_limit)
{
    int V = times.length;
    if(V == 2)
        return new int[]{};
    if(findNegativeCycle(times))
    {
        int ans[] = new int[times.length - 2];
        for(int i = 0; i < ans.length; i++)
          ans[i] = i;
        return ans;
    }
    lookup = new int[MEMO_SIZE];
    lookup_for_bunnies = new int[V];
    for(int i = 0; i < V; i++)
        lookup_for_bunnies[i] = -1;
    
    times_limit = bellmanFord(times, times_limit);
    int initial[] = new int[V];
    int res[] = new int[V];
    
    dfs(times, initial, 0, times_limit, res);
    
    int len = countArr(res);
    int ans[] = new int[len];
    int counter = 0;
    for(int i = 0; i < res.length; i++)
      if(res[i] == 1)
      {
        ans[counter++] = i - 1;
        if(counter == len)
          break;
      }
    
    return ans;
}

}