# 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 :

```                            ```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 PrintWriter out;

public static void main(String[] args) throws IOException {
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);
}

final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;

din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
}

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

public String readLine() throws IOException {
byte[] buf = new byte[1 << 20];
int cnt = 0;
while (c <= ' ')
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;
while (c <= ' ')
do {
buf[cnt++] = c;
} while ((c = read()) > ' ');
return new String(buf, 0, cnt);
}

public int nextInt() throws IOException {
int ret = 0;
while (c <= ' ')
boolean neg = (c == '-');
if (neg)
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;
while (c <= ' ')
boolean neg = (c == '-');
if (neg)
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;
while (c <= ' ')
boolean neg = (c == '-');
if (neg)
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 {
buffer[0] = -1;
}

private byte read() throws IOException {
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

Given a pointer to the head of a linked list, insert a new node before the head. The next value in the new node should point to head and the data value should be replaced with a given value. Return a reference to the new head of the list. The head pointer given may be null meaning that the initial list is empty. Function Description: Complete the function insertNodeAtHead in the editor below

## Insert a node at a specific position in a linked list

Given the pointer to the head node of a linked list and an integer to insert at a certain position, create a new node with the given integer as its data attribute, insert this node at the desired position and return the head node. A position of 0 indicates head, a position of 1 indicates one node away from the head and so on. The head pointer given may be null meaning that the initial list is e

## Delete a Node

Delete the node at a given position in a linked list and return a reference to the head node. The head is at position 0. The list may be empty after you delete the node. In that case, return a null value. Example: list=0->1->2->3 position=2 After removing the node at position 2, list'= 0->1->-3. Function Description: Complete the deleteNode function in the editor below. deleteNo

## Print in Reverse

Given a pointer to the head of a singly-linked list, print each data value from the reversed list. If the given list is empty, do not print anything. Example head* refers to the linked list with data values 1->2->3->Null Print the following: 3 2 1 Function Description: Complete the reversePrint function in the editor below. reversePrint has the following parameters: Sing