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

Is This a Binary Search Tree?

For the purposes of this challenge, we define a binary tree to be a binary search tree with the following ordering requirements: The data value of every node in a node's left subtree is less than the data value of that node. The data value of every node in a node's right subtree is greater than the data value of that node. Given the root node of a binary tree, can you determine if it's also a

View Solution →

Square-Ten Tree

The square-ten tree decomposition of an array is defined as follows: The lowest () level of the square-ten tree consists of single array elements in their natural order. The level (starting from ) of the square-ten tree consists of subsequent array subsegments of length in their natural order. Thus, the level contains subsegments of length , the level contains subsegments of length , the

View Solution →

Balanced Forest

Greg has a tree of nodes containing integer data. He wants to insert a node with some non-zero integer value somewhere into the tree. His goal is to be able to cut two edges and have the values of each of the three new trees sum to the same amount. This is called a balanced forest. Being frugal, the data value he inserts should be minimal. Determine the minimal amount that a new node can have to a

View Solution →

Jenny's Subtrees

Jenny loves experimenting with trees. Her favorite tree has n nodes connected by n - 1 edges, and each edge is ` unit in length. She wants to cut a subtree (i.e., a connected part of the original tree) of radius r from this tree by performing the following two steps: 1. Choose a node, x , from the tree. 2. Cut a subtree consisting of all nodes which are not further than r units from node x .

View Solution →

Tree Coordinates

We consider metric space to be a pair, , where is a set and such that the following conditions hold: where is the distance between points and . Let's define the product of two metric spaces, , to be such that: , where , . So, it follows logically that is also a metric space. We then define squared metric space, , to be the product of a metric space multiplied with itself: . For

View Solution →

Array Pairs

Consider an array of n integers, A = [ a1, a2, . . . . an] . Find and print the total number of (i , j) pairs such that ai * aj <= max(ai, ai+1, . . . aj) where i < j. Input Format The first line contains an integer, n , denoting the number of elements in the array. The second line consists of n space-separated integers describing the respective values of a1, a2 , . . . an .

View Solution →