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.

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 :


                            Solution in C :

In C++ :

using namespace std;
#define fre 	freopen("","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){
		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;
		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(){
	int t, M;
		for(int i=1;i<=N;++i){

In Java :

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++){
    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]);
                    temp[curpos] = Math.min( d + Math.abs(ma-j), temp[curpos]);
                if(curpos == 0) 
                    temp[j] = Math.min( d, temp[j]);
                    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]);
    static Scanner sc = new Scanner(;
    static int ni() { return sc.nextInt(); }
    static void print(Object... 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)
        b = newb


View More Similar Problems

No Prefix Set

There is a given list of strings where each string contains only lowercase letters from a - j, inclusive. The set of strings is said to be a GOOD SET if no string is a prefix of another string. In this case, print GOOD SET. Otherwise, print BAD SET on the first line followed by the string being checked. Note If two strings are identical, they are prefixes of each other. Function Descriptio

View Solution →

Cube Summation

You are given a 3-D Matrix in which each block contains 0 initially. The first block is defined by the coordinate (1,1,1) and the last block is defined by the coordinate (N,N,N). There are two types of queries. UPDATE x y z W updates the value of block (x,y,z) to W. QUERY x1 y1 z1 x2 y2 z2 calculates the sum of the value of blocks whose x coordinate is between x1 and x2 (inclusive), y coor

View Solution →

Direct Connections

Enter-View ( EV ) is a linear, street-like country. By linear, we mean all the cities of the country are placed on a single straight line - the x -axis. Thus every city's position can be defined by a single coordinate, xi, the distance from the left borderline of the country. You can treat all cities as single points. Unfortunately, the dictator of telecommunication of EV (Mr. S. Treat Jr.) do

View Solution →

Subsequence Weighting

A subsequence of a sequence is a sequence which is obtained by deleting zero or more elements from the sequence. You are given a sequence A in which every element is a pair of integers i.e A = [(a1, w1), (a2, w2),..., (aN, wN)]. For a subseqence B = [(b1, v1), (b2, v2), ...., (bM, vM)] of the given sequence : We call it increasing if for every i (1 <= i < M ) , bi < bi+1. Weight(B) =

View Solution →

Kindergarten Adventures

Meera teaches a class of n students, and every day in her classroom is an adventure. Today is drawing day! The students are sitting around a round table, and they are numbered from 1 to n in the clockwise direction. This means that the students are numbered 1, 2, 3, . . . , n-1, n, and students 1 and n are sitting next to each other. After letting the students draw for a certain period of ti

View Solution →

Mr. X and His Shots

A cricket match is going to be held. The field is represented by a 1D plane. A cricketer, Mr. X has N favorite shots. Each shot has a particular range. The range of the ith shot is from Ai to Bi. That means his favorite shot can be anywhere in this range. Each player on the opposite team can field only in a particular range. Player i can field from Ci to Di. You are given the N favorite shots of M

View Solution →