Saturday, December 21, 2013

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;
}