Question

Saving The Universe Again Problem An alien robot is threatening the universe, using a beam that...

Saving The Universe Again

Problem

An alien robot is threatening the universe, using a beam that will destroy all algorithms knowledge. We have to stop it!

Fortunately, we understand how the robot works. It starts off with a beam with a strength of 1, and it will run a program that is a series of instructions, which will be executed one at a time, in left to right order. Each instruction is of one of the following two types:

C (for "charge"): Double the beam's strength.

S (for "shoot"): Shoot the beam, doing damage equal to the beam's current strength.

For example, if the robot's program is SCCSSC, the robot will do the following when the program runs:

Shoot the beam, doing 1 damage.

Charge the beam, doubling the beam's strength to 2.

Charge the beam, doubling the beam's strength to 4.

Shoot the beam, doing 4 damage.

Shoot the beam, doing 4 damage.

Charge the beam, increasing the beam's strength to 8.

In that case, the program would do a total of 9 damage.

The universe's top algorithmists have developed a shield that can withstand a maximum total of D damage. But the robot's current program might do more damage than that when it runs.

The President of the Universe has volunteered to fly into space to hack the robot's program before the robot runs it. The only way the President can hack (without the robot noticing) is by swapping two adjacent instructions. For example, the President could hack the above program once by swapping the third and fourth instructions to make it SCSCSC. This would reduce the total damage to 7. Then, for example, the president could hack the program again to make it SCSSCC, reducing the damage to 5, and so on.

To prevent the robot from getting too suspicious, the President does not want to hack too many times. What is this smallest possible number of hacks which will ensure that the program does no more than D total damage, if it is possible to do so?

Input

The first line of the input gives the number of test cases, T. T test cases follow. Each consists of one line containing an integer Dand a string P: the maximum total damage our shield can withstand, and the robot's program.

Output

For each test case, output one line containing Case #x: y, where x is the test case number (starting from 1) and y is either the minimum number of hacks needed to accomplish the goal, or IMPOSSIBLE if it is not possible.

Limits

1 ? T ? 100.
1 ? D ? 109.
2 ? length of P ? 30.
Every character in P is either C or S.
Time limit: 20 seconds per test set.
Memory limit: 1GB.

Test set 1 (Visible)

The robot's program contains either zero or one C characters.

Test set 2 (Hidden)

No additional restrictions to the Limits section.

Sample


Input

Output
6
1 CS
2 CS
1 SS
6 SCCSSC
2 CC
3 CSCSS

Case #1: 1
Case #2: 0
Case #3: IMPOSSIBLE
Case #4: 2
Case #5: 0
Case #6: 5

Note that the last three sample cases would not appear in test set 1.

In Sample Case #1, the President can swap the two instructions to reduce the total damage to 1, which the shield can withstand.

In Sample Case #2, the President does not need to hack the program at all, since the shield can already withstand the 2 total damage it will cause.

In Sample Case #3, the program will do more damage than the shield can withstand, and hacking will do nothing to change this. The universe is doomed.

Sample Case #4 uses the program described in the problem statement. The statement demonstrates one way to reduce the total damage to 5 using two hacks. It is not possible to reduce the damage to 6 or less by using only one hack; remember that the President can only swap adjacent instructions.

In Sample Case #5, the robot will never shoot, and so it will never do any damage. No hacking is required.

In Sample Case #6, five hacks are required. Notice that even if two hacks swap the instructions at the same two positions, they still count as separate hacks.

Solution for Saving The Universe Again

0 0
Add a comment Improve this question Transcribed image text
Answer #1

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

public class SavingTheUniverseAgain {

    public static void main(String[] args) throws Exception {

        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));

        int T = Integer.parseInt(in.readLine());
        int cases = 1;

        while (T-->0) {

            StringTokenizer stk = new StringTokenizer(in.readLine());
            int shield = Integer.parseInt(stk.nextToken());
            char[] robot = stk.nextToken().toCharArray();

            int taken = findDamage(robot);
            int hacks = 0;
            boolean imposible = false;

            if (shield<taken) {
                while (shield<taken && !imposible) {
                    if (!bestHack(robot, taken)) {
                        imposible = true;
                    }else {
                        ++hacks;
                        taken = findDamage(robot);
                    }
                }
            }

            if(imposible)
                out.write("Case #"+cases+": IMPOSSIBLE\n");
            else
                out.write("Case #"+cases+": "+hacks+"\n");

            ++cases;
        }

        in.close();
        out.close();
    }

    private static int findDamage(char[] robot) {
        int damage = 1;
        int taken = 0;

        for (int i = 0; i < robot.length; i++) {
            if (robot[i]=='C') {
                damage*=2;
            }else {
                taken += damage;
            }
        }
        return taken;
    }

    private static boolean bestHack(char[] robot, int taken) {

        boolean found = false;

        for (int i = robot.length-1; i >0 && !found ; i--) {

            if(robot[i]=='S' && robot[i-1]=='C'){
                robot[i]= 'C';
                robot[i-1]= 'S';
                found = true;
            }
        }

        return found;
    }

}


SavingTheUniverseAgain [-/ldeaProjects/SavingTheUniverseAgain] -../src/SavingTheUniverseAgain.java ISavingTheUniverseAgain] S

Add a comment
Know the answer?
Add Answer to:
Saving The Universe Again Problem An alien robot is threatening the universe, using a beam that...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • C++ Inheritance Problem Step a: Suppose you are creating a fantasy role-playing game. In this game...

    C++ Inheritance Problem Step a: Suppose you are creating a fantasy role-playing game. In this game we have four different types of Creatures: Humans, Cyberdemons, Balrogs, and elves. To represent one of these Creatures we might define a Creature class as follows: class Creature { private: int type; // 0 Human, 1 Cyberdemon, 2 Balrog, 3 elf int strength; // how much damage this Creature inflicts int hitpoints; // how much damage this Creature can sustain string getSpecies() const; //...

  • Major Homework #2 Implement a C program major_hw2.c to solve the 15-puzzle problem using the A*...

    Major Homework #2 Implement a C program major_hw2.c to solve the 15-puzzle problem using the A* search algorithm. 1. Objectives • To gain more experience on using pointers and linked lists in C programs. • To learn how to solve problems using state space search and A* search algorithm. 2. Background A* search and 15-puzzle problem have been introduced in the class. For more information, please read the wiki page of 15-puzzle problem at https://en.wikipedia.org/wiki/15_puzzle, and the wiki page of...

  • Major Homework #2 Implement a C program major_hw2.c to solve the 15-puzzle problem using the A* s...

    Major Homework #2 Implement a C program major_hw2.c to solve the 15-puzzle problem using the A* search algorithm. Please include pictures that the code runs and shows the different states as it reaches goal state please. 1. Objectives • To gain more experience on using pointers and linked lists in C programs. • To learn how to solve problems using state space search and A* search algorithm. 2. Background A* search and 15-puzzle problem have been introduced in the class....

  • Assignment 6: Recursion Learning Outcomes • Learn how to craft solutions using recursion instead of loops....

    Assignment 6: Recursion Learning Outcomes • Learn how to craft solutions using recursion instead of loops. Instructions This assignment will be different than previous assignments (and most assignments which come after it). In this assignment, you will be crafting four solutions to four different problems. This assignment will also have special requirements regarding how you may code. You are not allowed to use assignment statements. This includes using preincement, postincrement, predecrement, and postdecrement. You are allowed to use assignment to...

  • Homework 3: Input Validation 1   Objectives control structures console-based user input using Scanner class writing complete...

    Homework 3: Input Validation 1   Objectives control structures console-based user input using Scanner class writing complete programs using two classes: client and supplier 2   User Interface Specification This is a console-based I/O program. Display should go to System.out (print or println) and the program will get user input using the Scanner class. The flow of execution should be as follows: When the program starts, display a one-line introduction to the user Display a menu with 5 options 1. validate zip...

  • Hi i will give you a thumbs up if you do this problem correctly. Sorting Analysis Code and Essay ...

    Hi i will give you a thumbs up if you do this problem correctly. Sorting Analysis Code and Essay Due: 4/22/2019(Monday) Introduction And now for something completely different.   Different sorting algorithms are better for different size data sets.   Other sorting algorithms are better for data sets of a specific type – for instance, data that is already ordered. In this assignment you will implement four different sorting algorithms and collect statistics for each of those algorithms while sorting multiple different...

  • please Identify the key points and main thesis of the article 2. Describe the skills you...

    please Identify the key points and main thesis of the article 2. Describe the skills you will need to develop to manage the hospital of the future. use critical analysis doing these questions Suggestion for writing assignmemnt make believe the reader has never read the article -what are the key points you would want the reader to know in order to understand the hospital of the future. In addition, managers, executives do not have time to read--so again what key...

  • If you’re using Visual Studio Community 2015, as requested, the instructions below should be exact but...

    If you’re using Visual Studio Community 2015, as requested, the instructions below should be exact but minor discrepancies may require you to adjust. If you are attempting this assignment using another version of Visual Studio, you can expect differences in the look, feel, and/or step-by-step instructions below and you’ll have to determine the equivalent actions or operations for your version on your own. INTRODUCTION: In this assignment, you will develop some of the logic for, and then work with, the...

  • Assignment Overview This programming assignment is intended to demonstrate your knowledge of the following:  Writing...

    Assignment Overview This programming assignment is intended to demonstrate your knowledge of the following:  Writing a while loop  Writing a for loop  Writing a while loop with a sentinel value Chocolate Coupons Foothill Fro-cho, LLC, gives customers a coupon every time they purchase a chocolate bar. After they earn a certain number of coupons, they qualify for a free chocolate bar, which they may use toward the purchase of a single chocolate bar. Usually, 7 is the...

  • STEP 1: In your own words define problem employees and the categories they may fall into....

    STEP 1: In your own words define problem employees and the categories they may fall into. For the second or last paragraph provide your opinion on which employee type is the most difficult. DEFINITION : I think that "problem employees" are employees that either directly or indirectly hinder the organization's mission or vision, and break down into roughly four categories. In general, problem employees can be classified into two broad categories - employees creating problems for the organization and employees...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT