Broken Necklace
You have a necklace of N red, white, or blue beads (3<=N<=350) some of which are red, others blue, and others white, arranged at random. Here are two examples for n=29:
1 2 1 2 r b b r b r r b r b b b r r b r r r w r b r w w b b r r b b b b b b r b r r b r b r r r b r r r r r r b r b r r r w Figure A Figure B r red bead b blue bead w white bead
The beads considered first and second in the text that follows have been marked in the picture.
The configuration in Figure A may be represented as a string of b's and r's, where b represents a blue bead and r represents a red one, as follows: brbrrrbbbrrrrrbrrbbrbbbbrrrrb .
Suppose you are to break the necklace at some point, lay it out straight, and then collect beads of the same color from one end until you reach a bead of a different color, and do the same for the other end (which might not be of the same color as the beads collected before this).
Determine the point where the necklace should be broken so that the most number of beads can be collected.
Example
For example, for the necklace in Figure A, 8 beads can be collected, with the breaking point either between bead 9 and bead 10 or else between bead 24 and bead 25.
In some necklaces, white beads had been included as shown in Figure B above. When collecting beads, a white bead that is encountered may be treated as either red or blue and then painted with the desired color. The string that represents this configuration will include the three symbols r, b and w.
Write a program to determine the largest number of beads that can be collected from a supplied necklace.
PROGRAM NAME: beads
INPUT FORMAT
Line 1: | N, the number of beads |
Line 2: | a string of N characters, each of which is r, b, or w |
SAMPLE INPUT (file beads.in)
29 wwwbbrwrbrbrrbrbrwrwwrbwrwrrb
OUTPUT FORMAT
A single line containing the maximum of number of beads that can be collected from the supplied necklace.SAMPLE OUTPUT (file beads.out)
11
OUTPUT EXPLANATION
Consider two copies of the beads (kind of like being able to runaround the ends). The string of 11 is marked.original 'split' v wwwbbrwrbrbrrbrbrwrwwrbwrwrrb|wwwbbrwrbrbrrbrbrwrwwrbwrwrrb ******|***** rrrrrb|bbbbb <-- assignments 5 x r 6 x b <-- 11 total
分析:
先找br或rb或rw……wb或bw……wr。例如:找到了bw……wr那么先数出b、r之间的w的个数,再从r开始往后数直到遇到b,然后从b往前数知道遇到r。注意从r还是往后数过的不要与从b往前数过的重复。最后三个数相加便得到了一种情况。
代码:
/* ID: jszhais1 PROG: beads LANG: C++ */ #include <fstream> using namespace std; char nextChar(int point,int &nextPoint,char *beads,int &length){ return point+1<length?beads[nextPoint=point+1]:beads[nextPoint=0]; } char preChar(int point,int &prePoint,char *beads,int &length){ return point==0?beads[prePoint=length-1]:beads[prePoint=point-1]; } int main(int argc, const char * argv[]) { ofstream fout("beads.out"); ifstream fin("beads.in"); char beads[351];int length=0,MAX=0;bool isin=false; while(fin>>length){ fin>>beads; for(int point=0 ; point<length ; point++) { int nextPoint=0,endP=-1, midCounter=0; char next=nextChar(point,nextPoint,beads,length); if(beads[point]!='w') { for(;next=='w';next=nextChar(nextPoint,nextPoint,beads,length), midCounter++); if(beads[point]!=next) { isin=true; int max=1+midCounter,wnextPoint=0; char wnext=nextChar(nextPoint,wnextPoint,beads,length); for(;(wnext=='w'||wnext==next)&&wnext!=endP;max++,wnext=nextChar(wnextPoint,wnextPoint,beads,length)); endP=(nextPoint+max-1)%length; int wprePoint=0; char wlast=preChar(point, wprePoint, beads, length); for(max++;(wlast=='w'||wlast==beads[point])&&wprePoint!=endP;max++,wlast=preChar(wprePoint, wprePoint, beads, length)); endP=0; if (max>MAX) { MAX=max; } } } } if(!isin) MAX=length; fout<<MAX<<endl;MAX=0;isin=false; } return 0; }
答案:Analysis: Broken Necklace Russ Cox In this problem, the necklace size is small enough (350) that we might as well just try breaking the necklace at each point and see how many beads can be collected. This will take approximately O(n^2) time, but n is small enough that it won't matter.
The code is slightly simple-minded in that we might count the same beads twice if they can be taken off either side of the break. This can only happen if all beads can be taken off the necklace, so we just check for that at the end.
#include <stdio.h> #include <string.h> #include <assert.h> #define MAXN 400 char necklace[MAXN]; int len; /* * Return n mod m. The C % operator is not enough because * its behavior is undefined on negative numbers. */ int mod(int n, int m) { while(n < 0) n += m; return n%m; } /* * Calculate number of beads gotten by breaking * before character p and going in direction dir, * which is 1 for forward and -1 for backward. */ int nbreak(int p, int dir) { char color; int i, n; color = 'w'; /* Start at p if going forward, bead before if going backward */ if(dir > 0) i = p; else i = mod(p-1, len); /* We use "n<len" to cut off loops that go around the whole necklace */ for(n=0; n<len; n++, i=mod(i+dir, len)) { /* record which color we're going to collect */ if(color == 'w' && necklace[i] != 'w') color = necklace[i]; /* * If we've chosen a color and see a bead * not white and not that color, stop */ if(color != 'w' && necklace[i] != 'w' && necklace[i] != color) break; } return n; } void main(void) { FILE *fin, *fout; int i, n, m; fin = fopen("beads.in", "r"); fout = fopen("beads.out", "w"); assert(fin != NULL && fout != NULL); fscanf(fin, "%d %s", &len, necklace); assert(strlen(necklace) == len); m = 0; for(i=0; i<len; i++) { n = nbreak(i, 1) + nbreak(i, -1); if(n > m) m = n; } /* * If the whole necklace can be gotten with a good * break, we'll sometimes count beads more than * once. this can only happen when the whole necklace * can be taken, when beads that can be grabbed from * the right of the break can also be grabbed from the left. */ if(m > len) m = len; fprintf(fout, "%d\n", m); exit (0); }Daniel Bundala had an O(n) solution:
Dynamic Programming is good method for solving this problem in O(N). If we consider two copies of the string we easy transform cyclic configuration of the necklace to linear. Now we can compute for each breaking point how many beads of the same color can be collected on the left and on the right from the breaking point. I show how we can compute it only for the left side. For right side it is analogical. Let r[p] and b[p] be the number of red / blue beads that can be collected, when necklace is broken in point p. If we know this and color of next bead (c) we can compute r[p+1] and b[p+1].r[0] = p[0] = 0 If c = 'r' then r[p+1] = r[p] + 1 and b[p+1] = 0 because the length of the blue beads is 0. if c = 'b' then b[p+1] = b[p] + 1 and r[p+1] = 0 if c = 'w' then both length of the red and length of blue beads can be longer. so r[p+1] = r[p]+1 and b[p+1] = b[p] + 1.The number of beads that can be collected in breaking point p is then max(left[r[p]], left[b[p]]) + max(right[r[p]], right[b[p]]). And the maximum from this value is answer for the problem.#include <stdio.h> #include <string.h> #include <algorithm> using namespace std; FILE *in,*out; int main () { in = fopen("beads.in", "r"); out = fopen ("beads.out", "w"); int n; char tmp[400], s[800]; fscanf(in, "%d %s", &n, tmp); strcpy(s, tmp); strcat(s, tmp); int left[800][2], right[800][2]; left[0][0] = left[0][1] = 0; for (int i=1; i<= 2 * n; i++){ if (s[i - 1] == 'r'){ left[i][0] = left[i - 1][0] + 1; left[i][1] = 0; } else if (s[i - 1] == 'b'){ left[i][1] = left[i - 1][1] + 1; left[i][0] = 0; } else { left[i][0] = left[i - 1][0] + 1; left[i][1] = left[i - 1][1] + 1; } } right[2 * n][0] = right[2 * n][1] = 0; for (int i=2 * n - 1; i >= 0; i--){ if (s[i] == 'r'){ right[i][0] = right[i + 1][0] + 1; right[i][1] = 0; } else if (s[i] == 'b'){ right[i][1] = right[i + 1][1] + 1; right[i][0] = 0; } else { right[i][0] = right[i + 1][0] + 1; right[i][1] = right[i + 1][1] + 1; } } int m = 0; for (int i=0; i<2 * n; i++) m = max(m, max(left[i][0], left[i][1]) + max(right[i][0], right[i][1])); m = min(m, n); fprintf(out, "%d\n", m); fclose(in); fclose(out); return 0; }Holland's Frank Takes has a potentially easier solution:
/* This solution simply changes the string s into ss, then for every starting // symbol it checks if it can make a sequence simply by repeatedly checking // if a sequence can be found that is longer than the current maximum one. */ #include <iostream> #include <fstream> using namespace std; int main() { fstream input, output; string inputFilename = "beads.in", outputFilename = "beads.out"; input.open(inputFilename.c_str(), ios::in); output.open(outputFilename.c_str(), ios::out); int n, max=0, current, state, i, j; string s; char c; input >> n >> s; s = s+s; for(i=0; i<n; i++) { c = (char) s[i]; if(c == 'w') state = 0; else state = 1; j = i; current = 0; while(state <= 2) { // dont go further in second string than starting position in first string while(j<n+i && (s[j] == c || s[j] == 'w')) { current++; j++; } // while state++; c = s[j]; } // while if(current > max) max = current; } // for output << max << endl; return 0; } // main
结果:
Thanks for your submission!USER: jim zhai [jszhais1] TASK: beads LANG: C++ Compiling... Compile: OK Executing... Test 1: TEST OK [0.000 secs, 3360 KB] Test 2: TEST OK [0.000 secs, 3360 KB] Test 3: TEST OK [0.000 secs, 3360 KB] Test 4: TEST OK [0.000 secs, 3360 KB] Test 5: TEST OK [0.000 secs, 3360 KB] Test 6: TEST OK [0.000 secs, 3360 KB] Test 7: TEST OK [0.000 secs, 3360 KB] Test 8: TEST OK [0.000 secs, 3360 KB] Test 9: TEST OK [0.000 secs, 3360 KB] All tests OK.Your program ('beads') produced all correct answers! This is your submission #8 for this problem. Congratulations!
Here are the test data inputs:
------- test 1 ---- 29 wwwbbrwrbrbrrbrbrwrwwrbwrwrrb ------- test 2 ---- 3 rrr ------- test 3 ---- 77 rwrwrwrwrwrwrwrwrwrwrwrwbwrwbwrwrwrwrwrwrwrwrwrwrwrwrwrwrwrwrwrwrwrwrwrwrwrwr ------- test 4 ---- 17 wwwwwwwwwwwwwwwww ------- test 5 ---- 50 bbrrrbrrrrrrrrbrbbbrbrrbrrrrbbbrbrbbbbbrbrrrbbrbbb ------- test 6 ---- 8 rrwwwwbb ------- test 7 ---- 200 rrrrrrrrrrrrrrrrrrrrbbbbbbbbbbbbbbbbbbbbrrrrrrrrrrrrrrrrrrrrbbbbbbbbbbbbbbbbbbbbrrrrrrrrrrrrrrrrrrrrbbbbbbbbbbbbbbbbbbbbrrrrrrrrrrrrrrrrrrrrbbbbbbbbbbbbbbbbbbbbrrrrrrrrrrrrrrrrrrrrbbbbbbbbbbbbbbbbbbbb ------- test 8 ---- 350 rrbbrbbbwbwwbwbbbbwwrrbbwbrwbrwbbbrbrwrwbrwwwrrbbrrwrbbrwbwrwwwrbrwwwwwrwbwwwrrbrrbbbrbrbbbrbbbrbbwbbbbbrbrrbrwwbrrrrwbwrwrbbwbwrbrbrwwbrrbwbrwwbwwwbrbwrwbwbrbbbwrbwwrrrbwbwbbbbbrrwwwrbrwwrbbwrbbrbbrbwrrwwbrrrbrwbrwwrbwbwrrrbwrwrrbrbbwrwrbrwwwrwbwrrwwwwrrrwrrwbbwrwwrwrbwwbwrrrrbbwrbbrbwwwwwbrbbrbbrbrwbbwbwwbbbbbwwwrbwwbbbwrwwbbrrwrwbwrrwwwrrrwrrwww ------- test 9 ---- 333 rwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbrwbKeep up the good work!