Dorsey Thief


Problem Statement :


Mr. Dorsey Dawson recently stole X grams of gold from ACME Jewellers. He is now on a train back home. To avoid getting caught by the police, he has to convert all the gold he has into paper money. He turns into a salesman and starts selling the gold in the train.

There are N passengers who have shown interest in buying the gold. The ith passenger agrees to buy ai grams of gold by paying vi dollars. Dawson wants to escape from the police and also maximize the profit. Can you help him maximize the profit?

Note: The ith passenger would buy exactly ai grams if the transaction is successful.

Input Format

The first line contains two space separated integers, N and X, where N is the number of passengers who agreed to buy and X is the stolen amount of gold (in grams).
N lines follow. Each line contains two space separated integers -vi  and ai, where vi is the the value which the ith passenger has agreed to pay in exchange for ai grams of gold.

Constraints

1 <= X <= 5000
1 <= N <= 10^6
all vi's and ai's are less than or equal to 10^6 and greater than 0.
Output Format

If it's possible for Dorsey to escape, print the maximum profit he can enjoy, otherwise print Got caught!.



Solution :



title-img


                            Solution in C :

In C++ :





#include <algorithm>
#include <iostream>
#include <cstring>
#include <cassert>
#include <iomanip>
#include <climits>
#include <cstdio>
#include <vector>
#include <string>
#include <stack>
#include <cmath>
#include <ctime>
#include <queue>
#include <list>
#include <map>
#include <set>

#define REP(i,n) for(int i = 0; i <(int)n; i++)
#define foreach(it,x) for(__typeof(x.begin()) it = x.begin() ;
   it!=x.end() ; it++ )

#ifdef KAZAR
    #define eprintf(...) fprintf(stderr, __VA_ARGS__)
#else
    #define eprintf(...)
#endif

using namespace std;

const int inf = (int)1e9 + 5757;

template<class T> inline void umax(T &a,T b){if(a<b) a = b;}
template<class T> inline void umin(T &a,T b){if(a>b) a = b;}
template<class T> inline T abs(T a){return a>0 ? a : -a;}
template<class T> inline T lcm(T a,T b){return a/gcd(a,b)*b;}

inline int read(){int x;scanf(" %d",&x);return x;}

const int N = 5050;

long long dp[N];
vector<int> g[N];
vector<int> a,b;

int main(){

#ifdef KAZAR
    freopen("f.i","r",stdin);
    freopen("f.cik","w",stdout);
    freopen("error","w",stderr);
#endif

    int n = read();
    int x = read();

    for(int i = 1; i <= n; i++){
        int a = read(), v = read();
        if(v <= x){
            g[v].push_back(a);
        }
    }

    for(int i = 1; i <= x; i++){
        sort(g[i].begin(), g[i].end());
        reverse(g[i].begin(), g[i].end());
        int cnt = min(5000 / i + 1,(int)g[i].size());
        for(int j = 0; j < cnt; j++){
            a.push_back(i);
            b.push_back(g[i][j]);
        }
    }

    memset(dp, -1, sizeof dp);

    dp[0] = 0;

    eprintf("%d\n",a.size());

    for(int i = 0; i < (int)a.size(); i++){
        for(int j = x; j >= 0; j--)
            if(dp[j] != -1 && j + a[i] <= x)
                umax(dp[j + a[i]],dp[j] + b[i]);
    }

    if(dp[x] == -1){
        puts("Got caught!");
    }else{
        cout << dp[x] << endl;
    }

    return 0;
}








In Java :





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

public class Solution {

	BufferedReader br;
	PrintWriter out;
	StringTokenizer st;
	boolean eof;

	void solve() throws IOException {
		int n = nextInt();
		int x = nextInt();

		long[] max = new long[x + 1];
		Arrays.fill(max, -1);
		max[0] = 0;

		long freeBonus = 0;

		List<Integer>[] byNeed = new List[x + 1];
		for (int i = 1; i <= x; i++) {
			byNeed[i] = new ArrayList<>(0);
		}

		for (int i = 0; i < n; i++) {
			int gain = nextInt();
			int need = nextInt();
			if (need == 0) {
				freeBonus += gain;
				continue;
			}
			if (need <= x) {
				byNeed[need].add(gain);
			}

		}

		for (int need = 1; need <= x; need++) {
			List<Integer> cur = byNeed[need];
			Collections.sort(cur);
			Collections.reverse(cur);
			for (int i = 0; (i + 1) * need <= x && i < cur.size(); i++) {
				int gain = cur.get(i);
				for (int j = x; j >= need; j--) {
					if (max[j - need] != -1) {
						max[j] = Math.max(max[j], max[j - need] + gain);
					}
				}
			}
		}

		if (max[x] == -1) {
			out.println("Got caught!");
		} else {
			out.println(max[x] + freeBonus);
		}
	}

	Solution() throws IOException {
		br = new BufferedReader(new InputStreamReader(System.in));
		out = new PrintWriter(System.out);
		solve();
		out.close();
	}

	public static void main(String[] args) throws IOException {
		new Solution();
	}

	String nextToken() {
		while (st == null || !st.hasMoreTokens()) {
			try {
				st = new StringTokenizer(br.readLine());
			} catch (Exception e) {
				eof = true;
				return null;
			}
		}
		return st.nextToken();
	}

	String nextString() {
		try {
			return br.readLine();
		} catch (IOException e) {
			eof = true;
			return null;
		}
	}

	int nextInt() throws IOException {
		return Integer.parseInt(nextToken());
	}

	long nextLong() throws IOException {
		return Long.parseLong(nextToken());
	}

	double nextDouble() throws IOException {
		return Double.parseDouble(nextToken());
	}
}








In C :





#include <stdio.h>
#include <stdlib.h>

int main()
{ 
    int n,x;
    scanf("%d %d",&n,&x);
    int v[n],a[n];
    int temp=0;
    while(temp<n){
                  scanf("%d %d",&v[temp],&a[temp]);
                  temp++;
    }
    
    long long int dp[x+1];
    dp[0]=0;
    for(int i=1;i<=x;i++){
            dp[i]=-100000000000000000;
    }
    
    temp=0;
    while(temp<n){
                  for(int j=x;j>=a[temp];j--){
                          dp[j]=(dp[j]>dp[j-a[temp]]+v[temp])?dp[j]:(dp[j-a[temp]]+v[temp]);
                  }
                  temp++;
    }
    if(dp[x]>0){
                printf("%lld",dp[x]);
    }else{
          printf("Got caught!");
    }

return 0;   
}
                        








View More Similar Problems

Contacts

We're going to make our own Contacts application! The application must perform two types of operations: 1 . add name, where name is a string denoting a contact name. This must store name as a new contact in the application. find partial, where partial is a string denoting a partial name to search the application for. It must count the number of contacts starting partial with and print the co

View Solution →

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 →