My Calendar

2014年3月4日 星期二

UVa Problem 12403 - Save Setu

UVa Problem 12403 - Save Setu

Time limit: 1.000 seconds

https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=16&page=show_problem&problem=3834

Rahaduzzaman Setu, (Roll - 12) of 13th batch, CSE, University of Dhaka is tremendously ill. He has been suffering from Multi Drug Resistant TB for a long time. Now, his left lung is damaged and beyond repair. No medicine is working on his body to ease his pain. It is urgent to operate on his left lung so that the disease doesn’t spread to his right lung. It can either be removed through surgery or transplanted. He comes from a modest family and it is difficult and impossible for them to bare his medical expenses anymore. Because of the money needed (12 million BDT) to transplant, it is his family’s decision to go with the surgery (3 million BDT). We must help them financially by raising money. But we must not be confined with that amount only to do the surgery. We must go for the Transplant. Our target will be to collect as much as possible to help our friend. If anyone wants to contribute now, please send me your contribution or contact me. Please contribute as much as you can to save a life that you saw every week for the first two years of your University life. Please contribute as per your abilities. Our combined effort may save a life. For more information, consult the link below. 

http://supportsetu.com/ 

However, in this problem, you have to build a software that can calculate the donations. Initially the total amount of money is 0 and in each time, two types of operations will be there. 1) ‘donate K’ (100 ≤ K ≤ 105 ), then you have to add K to the account. 2) ‘report’, report all the money currently in the account. 

Input 
The first line of input will contain T (1 ≤ T ≤ 100) denoting the number of operations. Then there will be T lines each containing two types of operations as given. You may assume that the input follows the restrictions above. 

Output 
For each ‘report’ operation, print the total amount of money in the account. 

Sample Input 
donate 
1000 
report 
donate 
500 
report 

Sample Output 
1000 
1500

解題方法: 當 operation 是 donate 將輸字加總, report 就將將總的數字print 出來

import java.util.Scanner;

class UvA12403 {

  public static void main(String[] args) 
  {
      
   Scanner scan = new Scanner(System.in);
   int donations = 0 ;
   
   int n = scan.nextInt(); //insert the numbers of operations
   
   for(int i = 0 ; i < n ; i ++)
   {
    String operations = scan.next();  
    if(operations.equals("donate"))
     donations += scan.nextInt();
    else
     System.out.println(donations);
   } 
 }

}

UVa Problem 621 - Secret Research

UVa Problem 621 - Secret Research

Time limit: 3.000 seconds


At a certain laboratory results of secret research are thoroughly encrypted. A result of a single experiment is stored as an information of its completion: ‘positive result’, ‘negative result’, ‘experiment failed’ or ‘experiment not completed’ The encrypted result constitutes a string of digits S, which may take one of the following forms: 
  •  positive result S = 1 or S = 4 or S = 78 
  •  negative result S = S35 
  •  experiment failed S = 9S4 
  •  experiment not completed S = 190S 
(A sample result S35 means that if we add digits 35 from the right hand side to a digit sequence then we shall get the digit sequence corresponding to a failed experiment) You are to write a program which decrypts given sequences of digits.

Input 
A integer n stating the number of encrypted results and then consecutive n lines, each containing a sequence of digits given as ASCII strings. 

Output 
For each analysed sequence of digits the following lines should be sent to output (in separate lines): + for a positive result - for a negative result * for a failed experiment ? for a not completed experiment


Sample Input 
78 
7835 
19078 
944 

Sample Output 
+
 - 
*

解題方法 : 這題也是非常簡單,只需要根據題目所給的條件實作即可

import java.util.Scanner;
class UvA621 {

 public static void main(String[] args) {
  
  Scanner scan = new Scanner(System.in);

  int n = scan.nextInt();
  
  for(int i = 0 ; i < n ; i++ )
  {
   String encryptedMessage = scan.next();
   if(encryptedMessage.equals("1") || encryptedMessage.equals("4") || encryptedMessage.equals("78"))
    System.out.println("+");
   else
   {
    if (encryptedMessage.endsWith("35"))
     System.out.println("-");
    else if (encryptedMessage.startsWith("9") && encryptedMessage.endsWith("4"))
     System.out.println("*");
    else if (encryptedMessage.startsWith("190") )
     System.out.println("?");
   }
   
   
  }
 
 }

}

UVa Problem 101 The Blocks Problems

Background 

Many areas of Computer Science use simple, abstract domains for both analytical and empirical studies. For example, an early AI study of planning and robotics (STRIPS) used a block world in which a robot arm performed tasks involving the manipulation of blocks.
In this problem you will model a simple block world under certain rules and constraints. Rather than determine how to achieve a specified state, you will ``program'' a robotic arm to respond to a limited set of commands.

The Problem 

The problem is to parse a series of commands that instruct a robot arm in how to manipulate blocks that lie on a flat table. Initially there are n blocks on the table (numbered from 0 to n-1) with block bi adjacent to block bi+1 for all 0 ≤ i < n − 1 as shown in the diagram below:


 Initial Blocks World

The valid commands for the robot arm that manipulates blocks are:
  • move a onto where a and b are block numbers, puts block a onto block b after returning any blocks that are stacked on top of blocks a and bto their initial positions.
  • move a over where a and b are block numbers, puts block a onto the top of the stack containing block b, after returning any blocks that are stacked on top of block a to their initial positions.
  • pile a onto where a and b are block numbers, moves the pile of blocks consisting of block a, and any blocks that are stacked above block a, onto block b. All blocks on top of block b are moved to their initial positions prior to the pile taking place. The blocks stacked above block a retain their order when moved.
  • pile a over where a and b are block numbers, puts the pile of blocks consisting of block a, and any blocks that are stacked above block a, onto the top of the stack containing block b. The blocks stacked above block a retain their original order when moved.
  • quitterminates manipulations in the block world.
Any command in which a = b or in which a and b are in the same stack of blocks is an illegal command. All illegal commands should be ignored and should have no affect on the configuration of blocks.

The Input 

The input begins with an integer n on a line by itself representing the number of blocks in the block world. You may assume that 0 < n< 25.The number of blocks is followed by a sequence of block commands, one command per line. Your program should process all commands until the quit command is encountered.You may assume that all commands will be of the form specified above. There will be no syntactically incorrect commands.

The Output 

The output should consist of the final state of the blocks world. Each original block position numbered i ( 0 ≤ i < n where n is the number of blocks) should appear followed immediately by a colon. If there is at least a block on it, the colon must be followed by one space, followed by a list of blocks that appear stacked in that position with each block number separated from other block numbers by a space. Don't put any trailing spaces on a line.There should be one line of output for each block position (i.e., n lines of output where n is the integer on the first line of input).

Sample Input 

10
move 9 onto 1
move 8 over 1
move 7 over 1
move 6 over 1
pile 8 over 6
pile 8 over 5
move 2 over 1
move 4 over 9
quit

Sample Output 

 0: 0
 1: 1 9 2 4
 2:
 3: 3
 4:
 5: 5 8 7 6
 6:
 7:
 8:
 9:


解題方法:這題最重要的是要明白題意,不會太難。從題目的要求發現可以採用Stack進行實作。


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;
import java.util.StringTokenizer;


public class UvA101 {
      public static Stack blocks[];
      public static int[] position;
      public static int numberOfblocks;
      public static String command ="";
      public static int a,b;
    
    public static void main(String[] args) throws IOException{
      // Defined Variable
    
      BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
      numberOfblocks = Integer.parseInt(buf.readLine());
      blocks = new Stack[numberOfblocks];
      position = new int[numberOfblocks];
      
      for(int i = 0; i < numberOfblocks; i++) {
          blocks[i] = new Stack(); // Initial number of empty stack
          blocks[i].push(i);
          position[i] = i;
      }
      
      while(!(command=buf.readLine()).equals("quit")){
       
       StringTokenizer token = new StringTokenizer(command);
       String aWord = token.nextToken();
          a = Integer.parseInt(token.nextToken());
          String bWord = token.nextToken();
           b = Integer.parseInt(token.nextToken());
       
          if(a==b || position[a]==position[b])
           continue;
      
          if(aWord.equals("move"))
          {
           if(bWord.equals("onto"))
           {
            moveOnto(a,b);
           }
           else if(bWord.equals("over"))
           {
            moveOver(a,b);
           }
          }
          else if(aWord.equals("pile"))
          {
           if(bWord.equals("onto"))
           {
            pileOnto(a,b);
           }
           else if(bWord.equals("over"))
           {
            pileOver(a,b);
           }
          }
          
      }
      
      for(int i = 0; i < blocks.length; i++) 
       System.out.println(answer(i));
    }
     public static void moveOnto(int a, int b) {
        clearAbove(b);
        moveOver(a, b);
     }
     
     public static void moveOver(int a, int b) {
      clearAbove(a);
         blocks[position[b]].push(blocks[position[a]].pop());
         position[a] = position[b];
      }
     
     public static void  pileOnto(int a, int b) {
      clearAbove(b);
         pileOver(a, b);
      }
     
     public static void pileOver(int a, int b) {
      Stack pile = new Stack();
         while(blocks[position[a]].peek() != a) {
             pile.push(blocks[position[a]].pop());
         }
         
         pile.push(blocks[position[a]].pop());
         while(!pile.isEmpty()) {
            int Tmp = pile.pop();
            blocks[position[b]].push(Tmp);
            position[Tmp] = position[b];
         }
      }
     
     public static void clearAbove(int block) {
      while(blocks[position[block]].peek() != block) {
             initial(blocks[position[block]].pop());
          }
      }
     
     /* 
      * Initial the blocks
      */
     
     public static void initial(int block) {   
         while(!blocks[block].isEmpty()) {
            initial(blocks[block].pop());
         }
         blocks[block].push(block);
         position[block] = block;
     }
     
     public static String answer(int index) {
         String Result = "";
         while(!blocks[index].isEmpty()) Result = " " + blocks[index].pop() + Result;
         Result = index + ":" + Result;
         return Result;
     }
  }

UVa Problem 12289 - One-Two-Three

UVa Problem 12289 - One-Two-Three

Time limit: 1.000 seconds

https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&category=24&problem=3710&mosmsg=Submission+received+with+ID+19897820

Your little brother has just learned to write one, two and three, in English. He has written a lot of those words in a paper, your task is to recognize them. Note that your little brother is only a child so he may make small mistakes: for each word, there might be at most one wrong letter. The word length is always correct. It is guaranteed that each letter he wrote is in lower-case, and each word he wrote has a unique interpretation.

Input 
The first line contains the number of words that your little brother has written. Each of the following lines contains a single word with all letters in lowercase. The words satisfy the constraints above: at most one letter might be wrong, but the word length is always correct. There will be at most 10 words in the input.

Output 
For each test case, print the numerical value of the word.

Sample Input 
3
owe
too
theee

Sample Output 
1
2
3

解題方法 : Input 敘述中提到每個word的長度一定是對的 那首先只要判斷字的長度是 5 肯定就是3. one 和 two 擇一判斷輸入的每個字元是否有兩個或以上的字元相等.


import java.util.Scanner;

class Uva12289 {
 public static void main(String args[]) {
  
  Scanner scan = new Scanner(System.in); 
  int n= scan.nextInt();
  for(int i = 0 ; i < n ;i++) {
   String inputWords = scan.next();
   if(inputWords.length() == 5 )
    System.out.println("3");
   else{
    int cnt = 0 ;
    if( inputWords.charAt(0)=='o')
     cnt++;
    if( inputWords.charAt(1)=='n')
     cnt++;
    if( inputWords.charAt(2)=='e')
     cnt++;
    
    if(cnt >=2 )
     System.out.println("1");
    else
     System.out.println("2");
   }      
  }   
 }

}

2014年3月3日 星期一

UVa Problem 100 The 3n+1 problem

The 3n + 1 problem

Time limit: 3.000 seconds

Background

Problems in Computer Science are often classified as belonging to a certain class of problems (e.g., NP, Unsolvable, Recursive). In this problem, you will be analyzing a property of an algorithm whose classification is not known for all possible inputs.

The Problem

Consider the following algorithm:

       1.   input n

       2.   print n

       3.    if n = 1 then STOP

       4.       if n is odd then n ←− 3n + 1

       5.       else  n ←− n/2

       6.     GOTO 2
Given the input 22, the following sequence of numbers will be printed 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1

It is conjectured that the algorithm above will terminate (when a 1 is printed) for any integral input value. Despite the simplicity of the algorithm, it is unknown whether this conjecture is true. It has been verified, however, for all integers n such that 0 < n < 1,000,000 (and, in fact, for many more numbers than this.)



Given an input n, it is possible to determine the number of numbers printed (including the 1). For a given n this is called the cycle-length of n. In the example above, the cycle length of 22 is 16.



For any two numbers i and j you are to determine the maximum cycle length over all numbers between i and j.


The Input

The input will consist of a series of pairs of integers i and j, one pair of integers per line. All integers
will be less than 10,000 and greater than 0.
You should process all pairs of integers and for each pair determine the maximum cycle length over
all integers between and including i and j.

You can assume that no operation overflows a 32-bit integer

The Output

For each pair of input integers i and j you should output i, j, and the maximum cycle length for
integers between and including i and j. These three numbers should be separated by at least one space
with all three numbers on one line and with one line of output for each line of input. The integers i
and j must appear in the output in the same order in which they appeared in the input and should be
followed by the maximum cycle length (on the same line).


Sample Input

1 10
100 200
201 210
900 1000
Sample Output

1 10 20
100 200 125
201 210 89
900 1000 174

解題方法:這題相當容易,只要根據題目所給的演算法就可以。但請注意系統給的測資 i 和 j 不一定是由小到大也有可能由大到小,所以要使用Math.min()的功能確定 i 和 j 那個比較小當for loop的初始值。

 import java.util.Scanner;
public class Problem100 
{
 public static void main(String[] args) 
 {
 
     Scanner scan = new Scanner(System.in);
     int from,to,max=0,temp;
   
  while(scan.hasNextInt())
  {
       from=scan.nextInt();
       to=scan.nextInt();
           
       for(int n=Math.min(from, to);n<=Math.max(from, to);n++)
       {
        temp=cycle_length(n);
        if(temp>max)
        {
         max=temp;
        }
       }  
       System.out.println(from + " " + to + " " + max); 
       max=0;
  }       
 } 
 // function cycle_length
 public static int cycle_length(int n)
 {
  int length=1;
  while(n!=1)
  {
   if((n%2)==1)
    n=3*n+1;  
   else
    n=n/2;
   length++;
  }
   return length;
 } // end function cycle_length

}// end class Main