在USACO中Chapter1,Section1的题目。记录以便日后查看。翻译及部分思路来自NOCOW。
你有一条由 N 个红色的,白色的,或蓝色的珠子组成的项链(3<=N<=350),珠子是随意安排的. 这里是 n=29 的二个例子:
package chapt1.section1; public class P4 { /** * 根据array填充R2L * @param array * @param a R2L数组 * @param s 将W当做R或者B */ public void fill(char[] array,int[] a,char s){ int n = array.length; a[0] = 1; for(int i = 1 ; i < n ; i++){ char ai = array[i]=='w' ? s : array[i]; char ai1 = array[i-1] == 'w' ? s : array[i-1]; if(ai == ai1) a[i] = a[i-1] + 1; else a[i] = 1; } if(array[n-1] == 'w' || array[n-1] == s){ a[0] = a[n-1] + 1; for(int i = 1; i < n ; i++){ char ai = array[i]=='w' ? s : array[i]; char ai1 = array[i-1] == 'w' ? s : array[i-1]; if(ai == ai1) a[i] = a[i-1] + 1; else break; } } } /** * 填充L2R * @param array * @param a L2R 数组 * @param s 将W当做R或B */ public void fill2(char[] array,int[] a,char s){ int n = array.length; a[n-1] = 1; for(int i = n-2 ; i >= 0 ; i--){ char ai = array[i]=='w' ? s : array[i]; char ai1 = array[i+1] == 'w' ? s : array[i+1]; if(ai == ai1) a[i] = a[i+1] + 1; else a[i] = 1; } if(array[0] == 'w' || array[0] == s){ a[n-1] = a[0] + 1; for(int i = n-2 ; i >= 0 ; i--){ char ai = array[i]=='w' ? s : array[i]; char ai1 = array[i+1] == 'w' ? s : array[i+1]; if(ai == ai1) a[i] = a[i+1] + 1; else a[i] = 1; } } } /** * 取两个数组中最大的值放入a1中 * @param a1 * @param a2 */ public void merge(int[] a1,int[] a2){ for(int i = 0; i < a1.length ; i++){ if(a2[i] > a1[i]) a1[i] = a2[i]; } } public void beads(char[] array){ int n = array.length; int[] rcw = new int[n]; //R2L数组,将W当做R cw为clockwise int[] bcw = new int[n]; //R2L数组,将W当做B int[] bccw = new int[n]; //L2R数组,将W当做R ccw为counter clockwise int[] rccw = new int[n]; //L2R数组,将W当做B boolean flag[] = {false,false}; //检查是否全部相同,即是否为RRRRRRRRRR或BBBBBB这样的串 for(int i = 0; i < n ; i++){ if(array[i] == 'r'){ flag[0] = true; } if(array[i] == 'b'){ flag[1] = true; } } if(flag[0] == false || flag[1] == false){ //如果是,结果为n System.out.println(n); return; }else{ //计算数组 fill(array,rcw,'r'); fill(array,bcw,'b'); fill2(array,rccw,'r'); fill2(array,bccw,'b'); //合并 merge(rcw,bcw); merge(rccw,bccw); //rcw rccw int sum = -1; for(int i = 0 ; i < n ; i++){ if(i == n-1){ if(sum < (rcw[i] + rccw[0])) sum = (rcw[i] + rccw[0]); }else{ if(sum < (rcw[i] + rccw[i+1])) sum = (rcw[i] + rccw[i+1]); } } System.out.println(sum); } } public static void main(String[] args){ String b = "wwwbbrwrbrbrrbrbrwrwwrbwrwrrr"; new P4().beads(b.toCharArray()); } }