Saturday, December 21, 2013

11854 - Egypt


Problem A: Egypt

A long time ago, the Egyptians figured out that a triangle with sides of length 3, 4, and 5 had a right angle as its largest angle. You must determine if other triangles have a similar property.

The Input

Input represents several test cases, followed by a line containing 0 0 0. Each test case has three positive integers, less than 30,000, denoting the lengths of the sides of a triangle.

The Output

For each test case, a line containing "right" if the triangle is a right triangle, and a line containing "wrong" if the triangle is not a right triangle.

Sample Input

6 8 10
25 52 60
5 12 13
0 0 0

Output for Sample Input

right
wrong
right
 
Solution: 
#include <stdio.h>

int main(){
 static int A, B, C, D; 
 while(scanf("%d %d %d", &A, &B, &C) == 3 && (A || B || C)){  
  if(A >= B){
   if(A > C){
    D = A;
    A = C;
    C = D;
   }
  }else if(B > C){
   D = B;
   B = C;
   C = D;
  } 
   
  if(A*A+B*B == C*C)
   printf("right\n");
  else
   printf("wrong\n");   
 }
 return 0;
}

11805 - Bafana Bafana


B
Bafana Bafana

Team practice is very important not only for programming contest but also for football. By team practice players can learn cooperating with team mates.  For playing as a team improvement of passing skill is very important. Passing is a great way of getting the ball upfield and reduces the risk of giving the ball away.

Carlos Alberto Parreira, the coach of Bafana Bafana, also wants his players to practice passing a lot. That’s why, while in the training camp for soccer world cup 2010, every day he asks all of the players who are present in practice to stand in a circle and practice passing. If N players are in practice, he gives each of the players a distinct number from 1 to N, and asks them to stand sequentially, so that player 2 will stand in right side of player 1 and player 3 will stand in right side of player 2, and so on. As they are in a circle, player 1 will stand right to player N.

The rule of passing practice is, Parreira will give the ball to player K, and practice will start. Practice will come to an end after P passes. In each pass, a player will give the ball to his partner who is in his immediate right side. After P passes, the player who owns the ball at that moment will give the ball back to Parreira.

Parreira wants to be ensured that his players practice according the rule. So he wants a program which will tell him which player will give him the ball back. So after taking the ball from the same person he can be happy that, the players play according to the rules. Otherwise he will ask them to start from beginning.


Input
Input starts with an integer T (T <= 1000), the number of test cases. Each test case will contain three integers, N (2 <= N <= 23), K (1 <= K <= N), P(1<=P<=200).

Output
For each test case, output a single line giving the case number followed by the Bafana player number who will give the ball to Parreira. See sample output for exact format.
Sample Input
Sample Output
3
5 2 5
6 3 5
4 1 3
Case 1: 2
Case 2: 2
Case 3: 4

Problemsetter: Md. Arifuzzaman Arif, Special Thanks: Muntasir Khan, Sohel Hafiz

Solution
#include <stdio.h>

int main(){
    static int T, t, N, K, P;
    scanf("%d", &T);
    for(t = 1; t <= T; t++){
        scanf("%d%d%d", &N, &K, &P);
        K = (K+P)%N;
        if(!K)
            K = N;
        printf("Case %d: %d\n", t, K);   
    }
    return 0;
}

11764 - Jumping Mario


D
Jumping Mario
Input: Standard Input
Output: Standard Output

Mario is in the final castle. He now needs to jump over few walls and then enter the Koopa’s Chamber where he has to defeat the monster in order to save the princess. For this problem, we are only concerned with the “jumping over the wall” part. You will be given the heights of N walls from left to right. Mario is currently standing on the first wall. He has to jump to the adjacent walls one after another until he reaches the last one. That means, he will make (N-1) jumps. A high jump is one where Mario has to jump to a taller wall, and similarly, a low jump is one where Mario has to jump to a shorter wall. Can you find out the total number of high jumps and low jumps Mario has to make?

Input
The first line of input is an integer T (T < 30) that indicates the number of test cases. Each case starts with an integer N (0 < N < 50) that determines the number of walls. The next line gives the height of the N walls from left to right. Each height is a positive integer not exceeding 10.

Output

For each case, output the case number followed by 2 integers, total high jumps and total low jumps, respectively. Look at the sample for exact format.

Sample Input                            Output for Sample Input

3
8
1 4 2 2 3 5 3 4
1
9
5
1 2 3 4 5

Case 1: 4 2
Case 2: 0 0
Case 3: 4 0

Problemsetter: Sohel Hafiz
Special Thanks: Shamim Hafiz 

Solution:  

#include <stdio.h>
int main(){
    static int T, t, W, X, Y, H, L;
    scanf("%d", &T);
    for(t = 1; t <= T; t++){
        H = L = 0;
        if(scanf("%d", &W) == 1 && W){
            scanf("%d", &X);
            while(--W){
                scanf("%d", &Y);
                if(X < Y) H++;
                else if(X > Y) L++;
                X = Y;  
            }
        }
        printf("Case %d: %d %d\n", t, H, L);
    }     
    return 0;
}

10035 - Primary Arithmetic

Problem B: Primary Arithmetic

Children are taught to add multi-digit numbers from right-to-left one digit at a time. Many find the "carry" operation - in which a 1 is carried from one digit position to be added to the next - to be a significant challenge. Your job is to count the number of carry operations for each of a set of addition problems so that educators may assess their difficulty.

Input

Each line of input contains two unsigned integers less than 10 digits. The last line of input contains 0 0.

Output

For each line of input except the last you should compute and print the number of carry operations that would result from adding the two numbers, in the format shown below.

Sample Input

123 456
555 555
123 594
0 0

Sample Output

No carry operation.
3 carry operations.
1 carry operation. 
 
Solution
#include <stdio.h>
#define M 10

int main(){
   unsigned long A,B;
   char SA[M],SB[M];
   int C,COUNT;
   while(scanf("%lu%lu",&A,&B) == 2 && (A || B)){
      COUNT = C = 0; 
      while(A||B){
         C = (C+A%10+B%10)/10;
         A /= 10;
         B /= 10;
         COUNT += C;
      }
  
      if(COUNT){
         if(COUNT == 1)
            printf("1 carry operation.\n");
         else
            printf("%d carry operations.\n",COUNT);     
      }else
         printf("No carry operation.\n");
   }
   return 0;
}
 

Wall Jumping






#include <stdio.h>
int main(){
    int T, t, W, X, Y, H, L;
    scanf("%d", &T);
    for(t = 1; t <= T; t++){
        H = L = 0;
        if(scanf("%d", &W) == 1 && W){
            scanf("%d", &X);
            while(--W){
                scanf("%d", &Y);
                if(X < Y) H++;
                else if(X > Y) L++;
                X = Y;  
            }
        }
        printf("Case %d: %d %d\n", t, H, L);
    }     
    return 0;
}

Swap two values

Write a C program to interchange values of two numbers.
#include <stdio.h>

int main(){
    int X, Y, Z;
  
    /*Using third variable Z*/
    X = 5;
    Y = 10;
    Z = X;
    X = Y;
    Y = Z;
    printf("X:%d Y:%d\n", X, Y);

    /*Without using third variable Z*/
    X = 5;
    Y = 10;
    X = X + Y;
    Y = X - Y;
    X = X - Y;
    printf("X:%d Y:%d\n", X, Y);
  
    /*Using bitwise operation*/
    X = 5;
    Y = 10;
    X = X ^ Y;
    Y = X ^ Y;
    X = X ^ Y;
    printf("X:%d Y:%d\n", X, Y);
  
    /*char swap using bitwise operation*/
    char x = 'x';
    char y = 'y';
    x = x ^ y;
    y = x ^ y;
    x = x ^ y;
    printf("x:%c y:%c\n", x, y);
    /*char swap using bitwise operation*/
    long a = 123456;
    long b = 654321;
    a = a ^ b;
    b = a ^ b;
    a = a ^ b;
    printf("a:%ld b:%ld\n", a, b);

    return 0;
}

10300 - Ecological Premium


Problem A
Ecological Premium
Input: standard input
Output: standard output
Time Limit: 1 second
Memory Limit: 32 MB
German farmers are given a premium depending on the conditions at their farmyard. Imagine the following simplified regulation: you know the size of each farmer's farmyard in square meters and the number of animals living at it. We won't make a difference between different animals, although this is far from reality. Moreover you have information about the degree the farmer uses environment-friendly equipment and practices, expressed in a single integer greater than zero. The amount of money a farmer receives can be calculated from these parameters as follows. First you need the space a single animal occupies at an average. This value (in square meters) is then multiplied by the parameter that stands for the farmer's environment-friendliness, resulting in the premium a farmer is paid per animal he owns. To compute the final premium of a farmer just multiply this premium per animal with the number of animals the farmer owns.
Input
The first line of input contains a single positive integer n (<20), the number of test cases. Each test case starts with a line containing a single integer f (0<f<20), the number of farmers in the test case. This line is followed by one line per farmer containing three positive integers each: the size of the farmyard in square meters, the number of animals he owns and the integer value that expresses the farmer’s environment-friendliness. Input is terminated by end of file. No integer in the input is greater than 100000 or less than 0.

Output
For each test case output one line containing a single integer that holds the summed burden for Germany's budget, which will always be a whole number. Do not output any blank lines.

Sample Input
3
5
1 1 1
2 2 2
3 3 3
2 3 4
8 9 2
3
9 1 8
6 12 1
8 1 1
3
10 30 40
9 8 5
100 1000 70
Sample Output
38
86
7445

(The Joint Effort Contest, Problem setter: Frank Hutter)

Solution:
#include <stdio.h>
int main(){  
   static int T, N, S, A, F, P;
   scanf("%d", &T);
   while(T--){
      scanf("%d", &N);
      P = 0;
      while(N--){
         scanf("%d%d%d", &S, &A, &F);
         P += S*F;
      }
      printf("%d\n", P);
    }
    return 0;
}
 

10038 - Jolly Jumpers

Problem E: Jolly Jumpers

A sequence of n > 0 integers is called a jolly jumper if the absolute values of the difference between successive elements take on all the values 1 through n-1. For instance,
1 4 2 3
is a jolly jumper, because the absolutes differences are 3, 2, and 1 respectively. The definition implies that any sequence of a single integer is a jolly jumper. You are to write a program to determine whether or not each of a number of sequences is a jolly jumper.

Input

Each line of input contains an integer n <= 3000 followed by n integers representing the sequence.

Output

For each line of input, generate a line of output saying "Jolly" or "Not jolly".

Sample Input

4 1 4 2 3
5 1 4 2 -1 6

Sample Output

Jolly
Not jolly
 
Solution:
#include <stdio.h>
#define MAX 3000
int main(){ 
   static int N, I, J, V[MAX], A[MAX];

   while(scanf("%d",&N) == 1){ 
      for(I = 0; I < N; I++){
         scanf("%d",&V[I]);
         A[I] = 0;        
      }
      J = N-1;
      for(I = 0; I < J; I++)
         A[abs(V[I]-V[I+1])] = 1;
      J = 1;
      for(I = 1; I < N; I++){
         if(!A[I]){
            J = 0;
            break;
         }
      }
      if(J)
         printf("Jolly\n");
      else 
         printf("Not jolly\n");
   }
   return 0;
}
 

494 - Kindergarten Counting Game


 Kindergarten Counting Game 

Everybody sit down in a circle. Ok. Listen to me carefully.
``Woooooo, you scwewy wabbit!''
Now, could someone tell me how many words I just said?

Input and Output

Input to your program will consist of a series of lines, each line containing multiple words (at least one). A ``word'' is defined as a consecutive sequence of letters (upper and/or lower case).
Your program should output a word count for each line of input. Each word count should be printed on a separate line.

Sample Input

Meep Meep!
I tot I taw a putty tat.
I did! I did! I did taw a putty tat.
Shsssssssssh ... I am hunting wabbits. Heh Heh Heh Heh ...

Sample Output

2
7
10
9
 
Solution:  
#include <stdio.h>
#define SIZE 99
#define NUM 128

int main(){ 
  char S[SIZE], CH[NUM], c;
  int s, F, C;
  for(s = 0; s < NUM; s++)
  CH[s] = s > 64 && s < 91 || s > 96 && s < 123; 
   
  while(gets(S) != NULL){
     F = C = s = 0;
     while((c = S[s++]) != '\0'){
        if(CH[c])
           F = 1;
        else if(F){
           C++;
           F = 0;
        }
     }
     printf("%d\n", C);
 }  
 return 0;
}

272 - TEX Quotes


 TeX Quotes 

TeX is a typesetting language developed by Donald Knuth. It takes source text together with a few typesetting instructions and produces, one hopes, a beautiful document. Beautiful documents use `` and " to delimit quotations, rather than the mundane " which is what is provided by most keyboards. Keyboards typically do not have an oriented double-quote, but they do have a left-single-quote ` and a right-single-quote '. Check your keyboard now to locate the left-single-quote key ` (sometimes called the ``backquote key") and the right-single-quote key ' (sometimes called the ``apostrophe" or just ``quote"). Be careful not to confuse the left-single-quote ` with the ``backslash" key \. TeX lets the user type two left-single-quotes `` to create a left-double-quote `` and two right-single-quotes '' to create a right-double-quote ''. Most typists, however, are accustomed to delimiting their quotations with the un-oriented double-quote ".
If the source contained
"To be or not to be," quoth the bard, "that is the question."
then the typeset document produced by TeX would not contain the desired form:
``To be or not to be," quoth the bard, ``that is the question."
In order to produce the desired form, the source file must contain the sequence:
``To be or not to be,'' quoth the bard, ``that is the question.''
You are to write a program which converts text containing double-quote (") characters into text that is identical except that double-quotes have been replaced by the two-character sequences required by TeX for delimiting quotations with oriented double-quotes. The double-quote (") characters should be replaced appropriately by either `` if the " opens a quotation and by '' if the " closes a quotation. Notice that the question of nested quotations does not arise: The first " must be replaced by ``, the next by '', the next by ``, the next by '', the next by ``, the next by '', and so on.

Input and Output

Input will consist of several lines of text containing an even number of double-quote (") characters. Input is ended with an end-of-file character. The text must be output exactly as it was input except that:
  • the first " in each pair is replaced by two ` characters: `` and
  • the second " in each pair is replaced by two ' characters: ''.

Sample Input

"To be or not to be," quoth the Bard, "that
is the question".
The programming contestant replied: "I must disagree.
To `C' or not to `C', that is The Question!"

Sample Output

``To be or not to be,'' quoth the Bard, ``that
is the question''.
The programming contestant replied: ``I must disagree.
To `C' or not to `C', that is The Question!''
 
Solution: 
#include <stdio.h>
#define SIZE 99

int main(){ 
  char S[SIZE], R[SIZE], c;
  int s, r, F;
  F = 1;
  while(gets(S) != NULL){
     s = r = 0;     
     while((c = S[s++]) != '\0'){
        if(c == '"'){
           if(F){
              R[r++] = '`'; 
              R[r++] = '`';
              F = 0;
           }else{
              R[r++] = '\'';
              R[r++] = '\'';
              F = 1;
           }    
        }else{
           R[r++] = c; 
        } 
     }
     R[r] = '\0';
     printf("%s\n", R);
 } 
 return 0;
}

Friday, December 20, 2013

458 - The Decoder



 The Decoder 

Write a complete program that will correctly decode a set of characters into a valid message. Your program should read a given file of a simple coded set of characters and print the exact message that the characters contain. The code key for this simple coding is a one for one character substitution based upon a single arithmetic manipulation of the printable portion of the ASCII character set.

Input and Output

For example: with the input file that contains:
1JKJ'pz'{ol'{yhklthyr'vm'{ol'Jvu{yvs'Kh{h'Jvywvyh{pvu5
1PIT'pz'h'{yhklthyr'vm'{ol'Pu{lyuh{pvuhs'I|zpulzz'Thjopul'Jvywvyh{pvu5
1KLJ'pz'{ol'{yhklthyr'vm'{ol'Kpnp{hs'Lx|pwtlu{'Jvywvyh{pvu5
your program should print the message:
*CDC is the trademark of the Control Data Corporation.
*IBM is a trademark of the International Business Machine Corporation.
*DEC is the trademark of the Digital Equipment Corporation.
Your program should accept all sets of characters that use the same encoding scheme and should print the actual message of each set of characters.

Sample Input

1JKJ'pz'{ol'{yhklthyr'vm'{ol'Jvu{yvs'Kh{h'Jvywvyh{pvu5
1PIT'pz'h'{yhklthyr'vm'{ol'Pu{lyuh{pvuhs'I|zpulzz'Thjopul'Jvywvyh{pvu5
1KLJ'pz'{ol'{yhklthyr'vm'{ol'Kpnp{hs'Lx|pwtlu{'Jvywvyh{pvu5

Sample Output

*CDC is the trademark of the Control Data Corporation.
*IBM is a trademark of the International Business Machine Corporation.
*DEC is the trademark of the Digital Equipment Corporation.
 
Solution: 
#include <stdio.h>
#define SIZE 99

int main(){ 
  char S[SIZE];
  int N; 
  while(gets(S) != NULL){
     N = 0;
     while(S[N] != '\0')
        S[N++] -= 7;
     printf("%s\n", S);
  }
  return 0;
}

103 - Stacking Boxes



 Stacking Boxes 

Background

Some concepts in Mathematics and Computer Science are simple in one or two dimensions but become more complex when extended to arbitrary dimensions. Consider solving differential equations in several dimensions and analyzing the topology of an n-dimensional hypercube. The former is much more complicated than its one dimensional relative while the latter bears a remarkable resemblance to its ``lower-class'' cousin.

The Problem

Consider an n-dimensional ``box'' given by its dimensions. In two dimensions the box (2,3) might represent a box with length 2 units and width 3 units. In three dimensions the box (4,8,9) can represent a box tex2html_wrap_inline40 (length, width, and height). In 6 dimensions it is, perhaps, unclear what the box (4,5,6,7,8,9) represents; but we can analyze properties of the box such as the sum of its dimensions.
In this problem you will analyze a property of a group of n-dimensional boxes. You are to determine the longest nesting string of boxes, that is a sequence of boxes tex2html_wrap_inline44 such that each box tex2html_wrap_inline46 nests in box tex2html_wrap_inline48 ( tex2html_wrap_inline50 .
A box D = ( tex2html_wrap_inline52 ) nests in a box E = ( tex2html_wrap_inline54 ) if there is some rearrangement of the tex2html_wrap_inline56 such that when rearranged each dimension is less than the corresponding dimension in box E. This loosely corresponds to turning box D to see if it will fit in box E. However, since any rearrangement suffices, box D can be contorted, not just turned (see examples below).
For example, the box D = (2,6) nests in the box E = (7,3) since D can be rearranged as (6,2) so that each dimension is less than the corresponding dimension in E. The box D = (9,5,7,3) does NOT nest in the box E = (2,10,6,8) since no rearrangement of D results in a box that satisfies the nesting property, but F = (9,5,7,1) does nest in box E since F can be rearranged as (1,9,5,7) which nests in E.
Formally, we define nesting as follows: box D = ( tex2html_wrap_inline52 ) nests in box E = ( tex2html_wrap_inline54 ) if there is a permutation tex2html_wrap_inline62 of tex2html_wrap_inline64 such that ( tex2html_wrap_inline66 ) ``fits'' in ( tex2html_wrap_inline54 ) i.e., if tex2html_wrap_inline70 for all tex2html_wrap_inline72 .

The Input

The input consists of a series of box sequences. Each box sequence begins with a line consisting of the the number of boxes k in the sequence followed by the dimensionality of the boxes, n (on the same line.)
This line is followed by k lines, one line per box with the n measurements of each box on one line separated by one or more spaces. The tex2html_wrap_inline82 line in the sequence ( tex2html_wrap_inline84 ) gives the measurements for the tex2html_wrap_inline82 box.
There may be several box sequences in the input file. Your program should process all of them and determine, for each sequence, which of the k boxes determine the longest nesting string and the length of that nesting string (the number of boxes in the string).
In this problem the maximum dimensionality is 10 and the minimum dimensionality is 1. The maximum number of boxes in a sequence is 30.

The Output

For each box sequence in the input file, output the length of the longest nesting string on one line followed on the next line by a list of the boxes that comprise this string in order. The ``smallest'' or ``innermost'' box of the nesting string should be listed first, the next box (if there is one) should be listed second, etc.
The boxes should be numbered according to the order in which they appeared in the input file (first box is box 1, etc.).
If there is more than one longest nesting string then any one of them can be output.

Sample Input

5 2
3 7
8 10
5 2
9 11
21 18
8 6
5 2 20 1 30 10
23 15 7 9 11 3
40 50 34 24 14 4
9 10 11 12 13 14
31 4 18 8 27 17
44 32 13 19 41 19
1 2 3 4 5 6
80 37 47 18 21 9

Sample Output

5
3 1 2 4 5
4
7 2 5 6
 
Solution: 
#include <stdio.h>
#define BOXN 30
#define BOXD 10

struct BOX {
   int D[BOXD];
} B[BOXN];

int BI[BOXN], BD[BOXN], LEN[BOXN], K, N, L, k, n, l, d, V;

int main(){  
   while(scanf("%d %d", &K, &N) == 2){
      /*Input Each Test Case*/ 
      for(k = 0; k < K; k++){
         BI[k] = k;
         for(n = 0; n < N; n++){
            scanf("%d", &d);   
            BD[n] = d; 
         }
         /*Sort of each sequence*/
         for(n = 0; n < N; n++){
            d = n;
            for(l = n+1; l < N; l++)
               if(BD[d] > BD[l])
                  d = l;
               B[k].D[n] = BD[d];
               BD[d] = BD[n];
         }/*End Sorting*/ 
      }/*End Input*/
  
      /*Sort boxes according to dimension's length*/
      for(k = 0; k < K; k++) 
         BD[k] = B[k].D[0];    
      /*Sort of each Box*/
      for(k = 0; k < K; k++){
         d = k;
         for(l = k+1; l < K; l++)
            if(BD[d] > BD[l])
               d = l;
            BD[d] = BD[k]; 
            n = BI[d];
            BI[d] = BI[k];  
            BI[k] = n;
      }/*End Sorting*/
       
      /*Algorithm of LIS*/
      LEN[BI[0]] = 1;
      L = 1;        
      for(k = 1; k < K; k++){
         l = 1;
         for(d = 0; d < k; d++){
            for(n = 0; n < N && B[BI[d]].D[n] < B[BI[k]].D[n]; n++);         
               if(n == N)
                  if(LEN[BI[d]] >= l){
                     BD[BI[k]] = BI[d];
                     l = LEN[BI[d]]+1;
                  }
         }
         LEN[BI[k]] = l; 
         if(L < l){
            V = BI[k];
            L = l;
         }
      }
          
      BI[0] = V;
      for(l = 1; l < L; l++){
         BI[l] = BD[V];
         V = BD[V];
      }
      printf("%d\n", L);
      for(l = L-1; l >= 0; l--)
         printf("%d ", BI[l]+1);
      printf("\n");
   }
   return 0;
}
 

Tuesday, December 17, 2013

102 - Ecological Bin Packing


 Ecological Bin Packing 

Background

Bin packing, or the placement of objects of certain weights into different bins subject to certain constraints, is an historically interesting problem. Some bin packing problems are NP-complete but are amenable to dynamic programming solutions or to approximately optimal heuristic solutions.
In this problem you will be solving a bin packing problem that deals with recycling glass.

The Problem

Recycling glass requires that the glass be separated by color into one of three categories: brown glass, green glass, and clear glass. In this problem you will be given three recycling bins, each containing a specified number of brown, green and clear bottles. In order to be recycled, the bottles will need to be moved so that each bin contains bottles of only one color.
The problem is to minimize the number of bottles that are moved. You may assume that the only problem is to minimize the number of movements between boxes.
For the purposes of this problem, each bin has infinite capacity and the only constraint is moving the bottles so that each bin contains bottles of a single color. The total number of bottles will never exceed 2^31.

The Input

The input consists of a series of lines with each line containing 9 integers. The first three integers on a line represent the number of brown, green, and clear bottles (respectively) in bin number 1, the second three represent the number of brown, green and clear bottles (respectively) in bin number 2, and the last three integers represent the number of brown, green, and clear bottles (respectively) in bin number 3. For example, the line 10 15 20 30 12 8 15 8 31
indicates that there are 20 clear bottles in bin 1, 12 green bottles in bin 2, and 15 brown bottles in bin 3.
Integers on a line will be separated by one or more spaces. Your program should process all lines in the input file.

The Output

For each line of input there will be one line of output indicating what color bottles go in what bin to minimize the number of bottle movements. You should also print the minimum number of bottle movements.
The output should consist of a string of the three upper case characters 'G', 'B', 'C' (representing the colors green, brown, and clear) representing the color associated with each bin.
The first character of the string represents the color associated with the first bin, the second character of the string represents the color associated with the second bin, and the third character represents the color associated with the third bin.
The integer indicating the minimum number of bottle movements should follow the string.
If more than one order of brown, green, and clear bins yields the minimum number of movements then the alphabetically first string representing a minimal configuration should be printed.

Sample Input

1 2 3 4 5 6 7 8 9
5 10 5 20 10 5 10 20 10

Sample Output

BCG 30
CBG 50 
 
Solution: 
#include <stdio.h>
#include <string.h>

struct GLASS {
   char COLOR[4];
   unsigned int COST;
} COM[6];


int main(){
   /*alphabetically order*/
   strcpy(COM[0].COLOR, "BCG");
   strcpy(COM[1].COLOR, "BGC");
   strcpy(COM[2].COLOR, "CBG");
   strcpy(COM[3].COLOR, "CGB");
   strcpy(COM[4].COLOR, "GBC");
   strcpy(COM[5].COLOR, "GCB"); 
   unsigned int T, B1, B2, B3, G1, G2, G3, C1, C2, C3;
   int I;
   while(scanf("%u%u%u%u%u%u%u%u%u", &B1, &G1, &C1, &B2, &G2, &C2, &B3, &G3, &C3) == 9){
      T = B1+B2+B3+G1+G2+G3+C1+C2+C3;  
      COM[0].COST = T - (B1 + C2 + G3);
      COM[1].COST = T - (B1 + G2 + C3);
      COM[2].COST = T - (C1 + B2 + G3);
      COM[3].COST = T - (C1 + G2 + B3);
      COM[4].COST = T - (G1 + B2 + C3);
      COM[5].COST = T - (G1 + C2 + B3);
      I = 0;
      for(T = 1; T < 6; T++) 
         if(COM[I].COST > COM[T].COST)
             I = T;             
    
      printf("%s %u\n", COM[I].COLOR, COM[I].COST);  
   } 
 
   return 0;
}
 

101 - The Blocks Problem



  The Blocks Problem 


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 \leq i < n-1$ as shown in the diagram below:
 
\begin{figure}
\centering
\setlength{\unitlength}{0.0125in} %
\begin{picture}
(2...
...raisebox{0pt}[0pt][0pt]{$\bullet
\bullet \bullet$ }}}
\end{picture}
\end{figure}
Figure: Initial Blocks World

The valid commands for the robot arm that manipulates blocks are:
  • move a onto b 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 b to their initial positions.
  • move a over b 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 b 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 b 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.
  • quit terminates 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 \leq 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:



Miguel Revilla
2000-04-06


Solution:

#include <stdio.h>
#include <string.h>

#define MAXN 25


struct TABLE { int LEN; int WHERE; int POS; int LIST[MAXN]; } BLOCK[MAXN];

void move_block(int B){
    int I, A, P, L;
    A = BLOCK[B].WHERE;
    P = BLOCK[B].POS+1;
    L = BLOCK[A].LEN;
    for(I = P; I < L; I++){
        B = BLOCK[A].LIST[I];
        BLOCK[B].WHERE = B;
        BLOCK[B].POS = BLOCK[B].LEN;
        BLOCK[B].LIST[BLOCK[B].LEN++] = B;               
    }
    BLOCK[A].LEN = P;
}

void move(int B1, int B2){
        int I, A, B, P, L, T;
        A = BLOCK[B1].WHERE;
        B = BLOCK[B2].WHERE;
        P = BLOCK[B1].POS;
        L = BLOCK[A].LEN;
        for(I = P; I < L; I++){
                T = BLOCK[A].LIST[I];
                BLOCK[T].WHERE = B;
                BLOCK[T].POS = BLOCK[B].LEN;
                BLOCK[B].LIST[BLOCK[B].LEN++] = T;               
        }
        BLOCK[A].LEN = P;
}

int main(){
    int N, I, A, B;
    char AC[5], WH[5];
    scanf("%d", &N);
    for(I = 0; I < N; I++){
        BLOCK[I].LEN = 1;
        BLOCK[I].WHERE = I;
        BLOCK[I].POS = 0;
        BLOCK[I].LIST[0] = I;
    }
   
    while(scanf("%s", AC)){
        if(strcmp(AC, "quit") == 0)
            break;
        scanf("%d%s%d", &A, WH, &B);

        if(A < 0 || A >= N || B < 0 || B >= N)
            continue;
        if(BLOCK[A].WHERE == BLOCK[B].WHERE)
            continue;
                   
        if(strcmp(AC, "move") == 0)
            move_block(A);
       
        if(strcmp(WH, "onto") == 0)
            move_block(B);
           
        move(A, B);               

    }
   
    for(I = 0; I < N; I++){
        printf("%d:", I);
        for(A = 0; A < BLOCK[I].LEN; A++)
            printf(" %d", BLOCK[I].LIST[A]);
        printf("\n");
    }
   
    return 0;
}