Two Robots


Problem Statement :


You have a warehouse with M containers filled with an infinite number of candies. The containers are arranged in a single row, equally spaced to be 1 meter apart. You also have 2 robots that can pick up 1 piece of candy and transport it between any two containers.

The robots take instructions in the form of queries consisting of two integers, Ma and Mb, respectively. To execute a query, a robot travels to container Ma, picks up 1 candy, transports it to container Mb, and then stops at Mb until it receives another query.

Calculate the minimum total distance the robots must travel to execute N queries in order.

Note: You choose which robot executes each query.

Input Format

The first line contains a single integer, T (the number of test cases); each of the T test cases is described over N+1 lines.

The first line of a test case has two space-separated integers, M (the number of containers) and N (the number of queries).
The N subsequent lines each contain two space-separated integers, Ma and Mb, respectively; each line Ni describes the ith query.

Constraints
1 <= T <= 50
1 < M <= 1000
1 <= N <= 1000
1 <= a,b <= M
Ma != Mb

Output Format

On a new line for each test case, print an integer denoting the minimum total distance that the robots must travel to execute the queries in order.



Solution :



title-img


                            Solution in C :

In C++ :





#include<bits/stdc++.h>
#include<iostream>
using namespace std;
#define fre 	freopen("0.in","r",stdin);freopen("0.out","w",stdout)
#define abs(x) ((x)>0?(x):-(x))
#define MOD 1000000007
#define fi first
#define se second
#define LL signed long long int
#define scan(x) scanf("%d",&x)
#define print(x) printf("%d\n",x)
#define scanll(x) scanf("%lld",&x)
#define printll(x) printf("%lld\n",x)
#define rep(i,from,to) for(int i=(from);i <= (to); ++i)
#define pii pair<int,int>

vector<int> G[2*100000+5];
int fdp[1005][1005];
LL dp[1005][1005], T=0;
pii Q[1000+5];
LL cost(int i,int j){
	if(i==0)
		return abs(Q[j].fi-Q[j].se);
	return abs(Q[j].fi-Q[j].se) + abs(Q[j].fi-Q[i].se);
}
int N;
LL rec(int i,int j){
	if(i==N or j==N)return 0;
	if(fdp[i][j]==T)
		return dp[i][j];
	fdp[i][j] = T;
	int k = max(i,j) + 1;
	return dp[i][j] = min(rec(k,j)+cost(i,k),rec(i,k)+cost(j,k));
}
int main(){
	//fre;
	int t, M;
	cin>>t;
	while(t--){
		T++;
		cin>>M>>N;
		for(int i=1;i<=N;++i){
			scan(Q[i].fi);
			scan(Q[i].se);
		}
		printll(rec(0,0));
	}
}








In Java :





import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args){
        int t = ni();
        for(int i=0; i<t; i++){
            solve();
        }
    }
    
    static void solve(){
        int m = ni(); int n = ni();
        long[] mindis = new long[m+1];
        long[] temp2;
        long[] temp = new long[m+1];
        Arrays.fill(mindis, Long.MAX_VALUE);
        int curpos = 0;//current position
        
        int ma, mb;
        long d;
        mindis[0] = 0;
        
        for(int i=0; i<n; i++){
            ma = ni(); mb = ni();
            
            Arrays.fill(temp, Long.MAX_VALUE);
            for(int j=0; j<=m; j++){
                if(mindis[j] == Long.MAX_VALUE) continue;
                d = mindis[j] + Math.abs(mb-ma);
                if(j == 0) 
                    temp[curpos] = Math.min( d , temp[curpos]);
                else
                    temp[curpos] = Math.min( d + Math.abs(ma-j), temp[curpos]);
                
                if(curpos == 0) 
                    temp[j] = Math.min( d, temp[j]);
                else
                    temp[j] = Math.min( d + Math.abs(ma-curpos) , temp[j]);
            }
            curpos = mb;
            temp2 = mindis;
            mindis = temp;
            temp = temp2;
        }
        
        long min = mindis[0];
        for(int i=0; i<=m; i++) min = Math.min(min, mindis[i]);
        System.out.println(min);
    }
    static Scanner sc = new Scanner(System.in);
    static int ni() { return sc.nextInt(); }
    
    static void print(Object... objs){
        System.out.println(Arrays.deepToString(objs));
    }
}








In C :





#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main() {
    int t, t1;
    scanf("%d", &t);
    for (t1 = 0; t1 < t; t1++) {
        int m, n, i, j, a, b;
        scanf("%d %d", &m, &n);
        int ar[m+1], r2 = 0, temp, min;
        for (j = 0; j <= m; j++) ar[j] = 0;
        for (i = 0; i < n; i++) {
            scanf("%d %d", &a, &b);
            min = ar[0] + abs(a - b);
            for (j = 1; j <= m; j++) {
                if (ar[j] == 0) continue;
                temp = ar[j] + abs(j - a) + abs(a - b);
                if (temp < min) min = temp;
            }
            if (r2 == 0) temp = abs(a - b);
            else temp = abs(r2 - a) + abs(a - b);
            ar[0] += temp;
            for (j = 1; j <= m; j++) {
                if (ar[j] == 0) continue;
                ar[j] += temp;
            }
            if (ar[r2] == 0 || ar[r2] > min) ar[r2] = min;
            r2 = b;
        }
        min = ar[0];
        for (j = 1; j <= m; j++) if (ar[j] != 0 && ar[j] < min) min = ar[j];
        printf("%d\n", min);
    }
    return 0;
}








In Python3 :





from collections import defaultdict

def dist(a, b):
    if -1 in (a, b): return 0
    return abs(a - b)

for _ in range(int(input())):
    m, n = [int(x) for x in input().split()]

    a, b = [int(x) for x in input().split()]
    dp = {-1: abs(b-a)}

    for _ in range(n-1):
        newa, newb = [int(x) for x in input().split()]
        d = abs(newa-newb) + dist(b, newa)
        d2 = min(v + dist(k, newa) + abs(newa-newb) for k, v in dp.items())
        for k in dp:
            dp[k] += d
        if b not in dp: dp[b] = float('inf')
        dp[b] = min(dp[b], d2)
        #print(dp)
        b = newb

    print(min(dp.values()))
                        








View More Similar Problems

Maximum Element

You have an empty sequence, and you will be given N queries. Each query is one of these three types: 1 x -Push the element x into the stack. 2 -Delete the element present at the top of the stack. 3 -Print the maximum element in the stack. Input Format The first line of input contains an integer, N . The next N lines each contain an above mentioned query. (It is guaranteed that each

View Solution →

Balanced Brackets

A bracket is considered to be any one of the following characters: (, ), {, }, [, or ]. Two brackets are considered to be a matched pair if the an opening bracket (i.e., (, [, or {) occurs to the left of a closing bracket (i.e., ), ], or }) of the exact same type. There are three types of matched pairs of brackets: [], {}, and (). A matching pair of brackets is not balanced if the set of bra

View Solution →

Equal Stacks

ou have three stacks of cylinders where each cylinder has the same diameter, but they may vary in height. You can change the height of a stack by removing and discarding its topmost cylinder any number of times. Find the maximum possible height of the stacks such that all of the stacks are exactly the same height. This means you must remove zero or more cylinders from the top of zero or more of

View Solution →

Game of Two Stacks

Alexa has two stacks of non-negative integers, stack A = [a0, a1, . . . , an-1 ] and stack B = [b0, b1, . . . , b m-1] where index 0 denotes the top of the stack. Alexa challenges Nick to play the following game: In each move, Nick can remove one integer from the top of either stack A or stack B. Nick keeps a running sum of the integers he removes from the two stacks. Nick is disqualified f

View Solution →

Largest Rectangle

Skyline Real Estate Developers is planning to demolish a number of old, unoccupied buildings and construct a shopping mall in their place. Your task is to find the largest solid area in which the mall can be constructed. There are a number of buildings in a certain two-dimensional landscape. Each building has a height, given by . If you join adjacent buildings, they will form a solid rectangle

View Solution →

Simple Text Editor

In this challenge, you must implement a simple text editor. Initially, your editor contains an empty string, S. You must perform Q operations of the following 4 types: 1. append(W) - Append W string to the end of S. 2 . delete( k ) - Delete the last k characters of S. 3 .print( k ) - Print the kth character of S. 4 . undo( ) - Undo the last (not previously undone) operation of type 1 or 2,

View Solution →