转载请注明出处
?
摘要:模拟, 环的处理
?
??????????PROGRAM NAME:beads
??????????INPUT FORMAT:
?? ? ? ? ?第 1 行: N, 珠子的数目
??????????第 2 行: 一串长度为N的字符串, 每个字符是 r , b 或 w。
??????????OUTPUT FORMAT:
?? ???????单独的一行包含从被供应的项
3. SAMPLE: ??????????SAMPLE INPUT: 29? wwwbbrwrbrbrrbrbrwrwwrbwrwrrb ??????????SAMPLE OUTPUT: ?? ???????11二. ?题解
1. 题意理解(将问题分析清楚,大致用什么思路): ?? ? ? ? ?这道题目的整体还是比较简单的,思路是从分割点分别向左、向右按题意搜索颜色相同的珠子,然后相加求最大即可。 ?? ? ? ? ?唯一的难点在于如何处理这个项链这个环?下面给出两种解法: ?? ? ? ? ?1. 将项链用一个链表表示,每一个珠子是一个结点。每次遍历到新的剪开位置时,只需将当前链表的头结点移动到尾结点即可。这样每一次还是分别从链表的头以及尾开始遍历。 ?? ? ? ? ?2. 用三条项链组成一个串,这样只需遍历中间那条项链,然后分别从剪开点向左与向右遍历即可。/*
ID: fightin1
LANG: JAVA
TASK: beads
*/
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.LinkedList;
public class beads {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
BufferedReader br = new BufferedReader(new FileReader("beads.in"));
PrintWriter pw = new PrintWriter (new FileWriter("beads.out"));
int length = Integer.parseInt(br.readLine());
String temp = br.readLine();
LinkedList<Character> necklace = new LinkedList<Character>();
for (int i=0;i<length;i++) {
necklace.add(temp.charAt(i));
}
int max = 0;
for (int i=0;i<length;i++) {
char remove = necklace.removeFirst();
char first = necklace.getFirst();
int position = 0;
necklace.addLast(remove);
int result = 0;
boolean allW = false;
if (necklace.getFirst()=='w'){
int end1 = find(necklace,0,length,0);
result = end1 + 1;
if (end1<necklace.size()-1){
int end2 = find (necklace,end1+1,length,0);
first = necklace.get(end2);
position = end2;
result = result + end2 - end1;
}else {
allW = true;
}
} else {
int end = find(necklace,0,length,0);
position = end ;
result = result + end + 1;
}
if (!allW){
if (necklace.getLast()=='w') {
int end1 = find(necklace, length-1,position,1);
int end2 = find(necklace,end1-1,position,1);
if (necklace.get(end2)==first){
result = result ;
}else {
result = result + length - end1;
result = result + end1 - end2 ;
}
}else {
if (necklace.getLast()==first){
result = result;
}else {
int end = find(necklace,length-1,position,1);
result = result + length - end ;
}
}
}
if (result >=max){
max = result;
}
}
pw.println(max);
pw.close();
br.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static int find(LinkedList<Character> necklace,int startPoint ,int endPoint,int direction){
if (direction ==0 ){
int i=startPoint+1;
for (;i<=endPoint-1;i++){
if (necklace.get(i)!=necklace.get(startPoint)&&necklace.get(i)!='w'){
break;
}
}
return i-1;
} else {
int i=startPoint-1;
for (;i>=endPoint+1;i--){
if (necklace.get(i)!=necklace.get(startPoint)&&necklace.get(i)!='w'){
break;
}
}
return i+1;
}
}
}
?