A Super Hero


Problem Statement :


Ma5termind is crazy about Action Games. He just bought a new one and got down to play it. Ma5termind usually finishes all the levels of a game very fast. But, This time however he got stuck at the very first level of this new game. Can you help him play this game.

To finish the game, Ma5termind has to cross N levels. At each level of the game, Ma5termind has to face M enemies. Each enemy has its associated power P and some number of bullets B. To knock down an enemy, Ma5termind needs to shoot him with one or multiple bullets whose collective count is equal to the power of the enemy. If Ma5termind manages to knock down any one enemy at a level, the rest of them run away and the level is cleared.

Here comes the challenging part of the game.
Ma5termind acquires all the bullets of an enemy once he has knocked him down. Ma5termind can use the bullets acquired after killing an enemy at ith level only till the (i+1)th level.

However, the bullets Ma5termind carried before the start of the game can be taken forward and can be used to kill more enemies.

Now, Ma5termind has to guess the minimum number of bullets he must have before the start of the game so that he clears all the N levels successfully.

NOTE

1.Bullets carried before the start of the game can be used to kill an enemy at any level.
2.One bullet decreases the power of an enemy by 1 Unit.
3.For better understanding of the problem look at the sample testcases.
Input Format

First line of input contains a single integer T denoting the number of test cases.
First line of each test case contains two space separated integers N and M denoting the number of levels and number of enemies at each level respectively.
Each of next N lines of a test case contain M space separated integers, where jth integer in the ith line denotes the power P of jth enemy on the ith level.
Each of the next N lines of a test case contains M space separated integers, where jth integer in the ih line denotes the number of bullets B jth enemy of ith level has.

Constraints
1 <= T <= 100
1 <= N <= 100
1 <= M <= 5*10^5
1 <= P,B <= 1000
For each test file, sum of N * M over all the test cases does not exceed 5*10^5.

Output Format

For each test case, print the required answer.



Solution :



title-img


                            Solution in C :

In C++ :





#include <bits/stdc++.h>
#define SZ(X) ((int)(X).size())
#define ALL(X) (X).begin(), (X).end()
#define REP(I, N) for (int I = 0; I < (N); ++I)
#define REPP(I, A, B) for (int I = (A); I < (B); ++I)
#define RI(X) scanf("%d", &(X))
#define RII(X, Y) scanf("%d%d", &(X), &(Y))
#define RIII(X, Y, Z) scanf("%d%d%d", &(X), &(Y), &(Z))
#define DRI(X) int (X); scanf("%d", &X)
#define DRII(X, Y) int X, Y; scanf("%d%d", &X, &Y)
#define DRIII(X, Y, Z) int X, Y, Z; scanf("%d%d%d", &X, &Y, &Z)
#define RS(X) scanf("%s", (X))
#define CASET int ___T, case_n = 1; scanf("%d ", &___T); while (___T-- > 0)
#define MP make_pair
#define PB push_back
#define MS0(X) memset((X), 0, sizeof((X)))
#define MS1(X) memset((X), -1, sizeof((X)))
#define LEN(X) strlen(X)
#define PII pair<int,int>
#define VPII vector<pair<int,int> >
#define PLL pair<long long,long long>
#define F first
#define S second
typedef long long LL;
using namespace std;
const int MOD = 1e9+7;
const int SIZE = 1e6+10;
int dp[101][1001];
int a[500001],b[500001];
int N,M;
int A(int x,int y){return a[x*M+y];}
int B(int x,int y){return b[x*M+y];}
void ff(int &x,int v){
    if(v==-1)return;
    if(x==-1||x>v)x=v;
}
int main(){
    CASET{
        MS1(dp);
        RII(N,M);
        int nn=0;
        REP(i,N)REP(j,M){
            RI(a[nn]);
            nn++;
        }
        nn=0;
        REP(i,N)REP(j,M){
            RI(b[nn]);
            nn++;
        }
        REP(j,1001)dp[0][j]=j;
        REP(i,N){
            REP(j,M){
                ff(dp[i+1][B(i,j)],dp[i][A(i,j)]);
            }
            for(int j=999;j>=0;j--)ff(dp[i+1][j],dp[i+1][j+1]);
            REP(j,1000)ff(dp[i+1][j+1],dp[i+1][j]+1);
        }
        printf("%d\n",dp[N][0]);
    }
    return 0;
}








In Java :





import java.io.*;
import java.util.*;

public class Solution {
  private static Reader in;
  private static PrintWriter out;

  public static void main(String[] args) throws IOException {
    in = new Reader();
    out = new PrintWriter(System.out, true);
    int T = in.nextInt();
    while(T-- > 0) {
      int N = in.nextInt(), M = in.nextInt();
      
      int[][] p = new int[N][M];
      for (int i = 0; i < N; i++) for (int j = 0; j < M; j++)
        p[i][j] = in.nextInt();
      int[][] b = new int[N][M];
      for (int i = 0; i < N; i++) for (int j = 0; j < M; j++)
        b[i][j] = in.nextInt();
      
      int[] dp = new int[1001];
      for (int i = N-1; i >= 0; i--) {
        int[] next = new int[1001];
        Arrays.fill(next, 1 << 29);
        for (int j = 0; j < M; j++) {
          for (int k = 0; k <= 1000; k++) {
            next[k] = Math.min(next[k], dp[b[i][j]] + (k < p[i][j] ? p[i][j]-k : 0));
          }
        }
        for (int j = 1; j <= 1000; j++)
          next[j] = Math.min(next[j], next[j-1]);
        dp = next;
      }
      
      int min = 1 << 29;
      for (int i = 0; i <= 1000; i++)
        min = Math.min(min, i + dp[i]);
      out.println(min);
    }
    out.close();
    System.exit(0);
  }

  static class Reader {
    final private int BUFFER_SIZE = 1 << 16;
    private DataInputStream din;
    private byte[] buffer;
    private int bufferPointer, bytesRead;

    public Reader() {
      din = new DataInputStream(System.in);
      buffer = new byte[BUFFER_SIZE];
      bufferPointer = bytesRead = 0;
    }

    public Reader(String file_name) throws IOException {
      din = new DataInputStream(new FileInputStream(file_name));
      buffer = new byte[BUFFER_SIZE];
      bufferPointer = bytesRead = 0;
    }

    public String readLine() throws IOException {
      byte[] buf = new byte[1 << 20];
      int cnt = 0;
      byte c = read();
      while (c <= ' ')
        c = read();
      do {
        buf[cnt++] = c;
      } while ((c = read()) != '\n');
      return new String(buf, 0, cnt);
    }

    public String next() throws IOException {
      byte[] buf = new byte[1 << 20];
      int cnt = 0;
      byte c = read();
      while (c <= ' ')
        c = read();
      do {
        buf[cnt++] = c;
      } while ((c = read()) > ' ');
      return new String(buf, 0, cnt);
    }

    public int nextInt() throws IOException {
      int ret = 0;
      byte c = read();
      while (c <= ' ')
        c = read();
      boolean neg = (c == '-');
      if (neg)
        c = read();
      do {
        ret = ret * 10 + c - '0';
      } while ((c = read()) >= '0' && c <= '9');
      if (neg)
        return -ret;
      return ret;
    }

    public long nextLong() throws IOException {
      long ret = 0;
      byte c = read();
      while (c <= ' ')
        c = read();
      boolean neg = (c == '-');
      if (neg)
        c = read();
      do {
        ret = ret * 10 + c - '0';
      } while ((c = read()) >= '0' && c <= '9');
      if (neg)
        return -ret;
      return ret;
    }

    public double nextDouble() throws IOException {
      double ret = 0, div = 1;
      byte c = read();
      while (c <= ' ')
        c = read();
      boolean neg = (c == '-');
      if (neg)
        c = read();
      do {
        ret = ret * 10 + c - '0';
      } while ((c = read()) >= '0' && c <= '9');
      if (c == '.')
        while ((c = read()) >= '0' && c <= '9')
          ret += (c - '0') / (div *= 10);
      if (neg)
        return -ret;
      return ret;
    }

    private void fillBuffer() throws IOException {
      bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
      if (bytesRead == -1)
        buffer[0] = -1;
    }

    private byte read() throws IOException {
      if (bufferPointer == bytesRead)
        fillBuffer();
      return buffer[bufferPointer++];
    }

    public void close() throws IOException {
      if (din == null)
        return;
      din.close();
    }
  }


}








In C :






#include <stdio.h>
#include <stdlib.h>
int get_i(int*a,int num,int size);
int med(int*a,int size);
void sort_a2(int*a,int*b,int size);
void merge2(int*a,int*left_a,int*right_a,int*b,int*left_b,int*right_b,int left_size, int right_size);
int min1[500000],min2[500000];

int main(){
  int T,N,M,min,m1,i,j,k;
  int **table,**dp;
  scanf("%d",&T);
  while(T--){
    scanf("%d%d",&N,&M);
    table=(int**)malloc(2*N*sizeof(int*));
    dp=(int**)malloc(N*sizeof(int*));
    for(i=0;i<2*N;i++)
      table[i]=(int*)malloc(M*sizeof(int));
    for(i=0;i<N;i++)
      dp[i]=(int*)malloc(M*sizeof(int));
    for(i=0;i<2*N;i++)
      for(j=0;j<M;j++)
        scanf("%d",&table[i][j]);
    for(i=0;i<N;i++)
      sort_a2(table[i],table[i+N],M);
    for(i=M-1;i>=0;i--){
      dp[0][i]=min1[i]=0;
      if(i==M-1)
        min2[i]=table[N-1][i];
      else
        min2[i]=(min2[i+1]<table[N-1][i])?min2[i+1]:table[N-1][i];
    }
    for(i=N-2;i>=0;i--){
      for(j=0;j<M;j++){
        m1=-1;
        k=get_i(table[i+1],table[i+N][j]+1,M);
        if(k!=M)
          m1=min2[k]-table[i+N][j];
        if(k && (m1==-1 || min1[k-1]<m1))
          m1=min1[k-1];
        dp[N-i-1][j]=m1;
      }
      min1[0]=dp[N-i-1][0];
      for(j=1;j<M;j++)
        min1[j]=(min1[j-1]<dp[N-i-1][j])?min1[j-1]:dp[N-i-1][j];
      min2[M-1]=dp[N-i-1][M-1]+table[i][M-1];
      for(j=M-2;j>=0;j--)
        min2[j]=(min2[j+1]<dp[N-i-1][j]+table[i][j])?min2[j+1]:(dp[N-i-1][j]+table[i][j]);
    }
    min=-1;
    for(i=0;i<M;i++)
      if(min==-1 || dp[N-1][i]+table[0][i]<min)
        min=dp[N-1][i]+table[0][i];
    printf("%d\n",min);
    for(i=0;i<2*N;i++)
      free(table[i]);
    free(table);
    for(i=0;i<N;i++)
      free(dp[i]);
    free(dp);
  }
  return 0;
}
int get_i(int*a,int num,int size){
  if(size==0)
    return 0;
  if(num>med(a,size))
    return get_i(&a[(size+1)>>1],num,size>>1)+((size+1)>>1);
  else
    return get_i(a,num,(size-1)>>1);
}
int med(int*a,int size){
  return a[(size-1)>>1];
}
void sort_a2(int*a,int*b,int size){
  if (size < 2)
    return;
  int m = (size+1)/2,i;
  int*left_a,*left_b,*right_a,*right_b;
  left_a=(int*)malloc(m*sizeof(int));
  right_a=(int*)malloc((size-m)*sizeof(int));
  left_b=(int*)malloc(m*sizeof(int));
  right_b=(int*)malloc((size-m)*sizeof(int));
  for(i=0;i<m;i++){
    left_a[i]=a[i];
    left_b[i]=b[i];
  }
  for(i=0;i<size-m;i++){
    right_a[i]=a[i+m];
    right_b[i]=b[i+m];
  }
  sort_a2(left_a,left_b,m);
  sort_a2(right_a,right_b,size-m);
  merge2(a,left_a,right_a,b,left_b,right_b,m,size-m);
  free(left_a);
  free(right_a);
  free(left_b);
  free(right_b);
  return;
}
void merge2(int*a,int*left_a,int*right_a,int*b,int*left_b,int*right_b,int left_size, int right_size)
{
  int i = 0, j = 0;
  while (i < left_size|| j < right_size) {
    if (i == left_size) {
      a[i+j] = right_a[j];
      b[i+j] = right_b[j];
      j++;
    } else if (j == right_size) {
      a[i+j] = left_a[i];
      b[i+j] = left_b[i];
      i++;
    } else if (left_a[i] <= right_a[j]) {
      a[i+j] = left_a[i];
      b[i+j] = left_b[i];
      i++;
    } else {
      a[i+j] = right_a[j];
      b[i+j] = right_b[j];
      j++;
    }
  }
  return;
}








In Python3 :






Inf = 1000*5*100000 + 1

def solve(N,M,P,B) :
    Bmax = max(max(b) for b in B) + 1
    s,sb = [Inf]*Bmax, [Inf]*Bmax
    for m in range(M) :
        b = B[0][m]
        while b >= 0 and P[0][m] < s[b] :
            s[b] = P[0][m]
            b -= 1
        b = B[0][m]
        while b < Bmax and P[0][m]-B[0][m] < sb[b] :
            sb[b] = P[0][m] - B[0][m]
            b += 1

    for n in range(1,N) :
#        print((s,sb))
        s_,sb_ = [Inf]*Bmax, [Inf]*Bmax
        for m in range(M) :
            if P[n][m] < Bmax :
                v = min(sb[P[n][m]]+P[n][m], s[P[n][m]])
            else :
                v = sb[Bmax-1] + P[n][m]
            b = B[n][m]
            while b >= 0 and v < s_[b] :
                s_[b] = v
                b -= 1
            b = B[n][m]
            while b < Bmax and v-B[n][m] < sb_[b] :
                sb_[b] = v - B[n][m]
                b += 1
        s,sb = s_,sb_
            
    return min(s)

T = int(input())
for _ in range(T) :
    N, M = (int(_) for _ in input().split())
    P = [[int(_) for _ in input().split()] for _ in range(N)]
    B = [[int(_) for _ in input().split()] for _ in range(N)]
    print(solve(N,M,P,B))
                        








View More Similar Problems

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 →

Waiter

You are a waiter at a party. There is a pile of numbered plates. Create an empty answers array. At each iteration, i, remove each plate from the top of the stack in order. Determine if the number on the plate is evenly divisible ith the prime number. If it is, stack it in pile Bi. Otherwise, stack it in stack Ai. Store the values Bi in from top to bottom in answers. In the next iteration, do the

View Solution →

Queue using Two Stacks

A queue is an abstract data type that maintains the order in which elements were added to it, allowing the oldest elements to be removed from the front and new elements to be added to the rear. This is called a First-In-First-Out (FIFO) data structure because the first element added to the queue (i.e., the one that has been waiting the longest) is always the first one to be removed. A basic que

View Solution →

Castle on the Grid

You are given a square grid with some cells open (.) and some blocked (X). Your playing piece can move along any row or column until it reaches the edge of the grid or a blocked cell. Given a grid, a start and a goal, determine the minmum number of moves to get to the goal. Function Description Complete the minimumMoves function in the editor. minimumMoves has the following parameter(s):

View Solution →

Down to Zero II

You are given Q queries. Each query consists of a single number N. You can perform any of the 2 operations N on in each move: 1: If we take 2 integers a and b where , N = a * b , then we can change N = max( a, b ) 2: Decrease the value of N by 1. Determine the minimum number of moves required to reduce the value of N to 0. Input Format The first line contains the integer Q.

View Solution →

Truck Tour

Suppose there is a circle. There are N petrol pumps on that circle. Petrol pumps are numbered 0 to (N-1) (both inclusive). You have two pieces of information corresponding to each of the petrol pump: (1) the amount of petrol that particular petrol pump will give, and (2) the distance from that petrol pump to the next petrol pump. Initially, you have a tank of infinite capacity carrying no petr

View Solution →