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

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 →

Poisonous Plants

There are a number of plants in a garden. Each of the plants has been treated with some amount of pesticide. After each day, if any plant has more pesticide than the plant on its left, being weaker than the left one, it dies. You are given the initial values of the pesticide in each of the plants. Determine the number of days after which no plant dies, i.e. the time after which there is no plan

View Solution →

AND xor OR

Given an array of distinct elements. Let and be the smallest and the next smallest element in the interval where . . where , are the bitwise operators , and respectively. Your task is to find the maximum possible value of . Input Format First line contains integer N. Second line contains N integers, representing elements of the array A[] . Output Format Print the value

View Solution →