problem Link  : 

I know, up on top you are seeing great sights, But down at the bottom, we, too, should have rights. We turtles can’t stand it. Our shells will all crack! Besides, we need food. We are starving!” groaned Mack. Mack, in an effort to avoid being cracked, has enlisted your advice as to the order in which turtles should be dispatched to form Yertle’s throne. Each of the five thousand, six hundred and seven turtles ordered by Yertle has a different weight and strength. Your task is to build the largest stack of turtles possible. Input Standard input consists of several lines, each containing a pair of integers separated by one or more space characters, specifying the weight and strength of a turtle. The weight of the turtle is in grams. The strength, also in grams, is the turtle’s overall carrying capacity, including its own weight. That is, a turtle weighing 300g with a strength of 1000g could carry 700g of turtles on its back. There are at most 5,607 turtles. Output Your output is a single integer indicating the maximum number of turtles that can be stacked without exceeding the strength of any one.

Sample Input 300 1000 1000 1200 200 600 100 101

Sample Output 3

Code Examples

#1 Code Example with C Programming

Code - C Programming

 #include <bits/stdc++.h>
using namespace std;

int main() {
    vector < pair<int,int>> turtles;
    int w,s;
    while(scanf("%d %d",&w,&s) == 2) {
    // (greedy) sort by min strength, because they can carry less
    sort(turtles.begin(), turtles.end());
    vector<int> dp(turtles.size(),1e7); // dp of minimum weight for stack size i
    dp[0] = 0;
    int res = 0;
    for(int i=0;i < turtles.size();i++){
        for(int j=res;j>=0;j--){
            if(turtles[i].first - turtles[i].second - dp[j] < 0) continue;
            dp[j+1] = min(dp[j+1], dp[j]+turtles[i].second); // minimize stack weight
            res = max(res, j+1);
    printf("%d\n", res>;
Copy The Code & Try With Live Editor


300 1000
1000 1200
200 600
100 101




UVA Online Judge solution - 10154 - Weights and Measures - UVA Online Judge solution in C,C++,Java 

UVA Online Judge solution - 10152-ShellSort - UVA Online Judge solution in C,C++,Java
UVA Online Judge solution - 10163-Storage Keepers - UVA Online Judge solution in C,C++,Java