結果

問題 No.1924 3 color painting on a line
ユーザー 37zigen
提出日時 2022-04-24 20:56:09
言語 Java
(openjdk 23)
結果
AC  
実行時間 326 ms / 2,000 ms
コード長 1,952 bytes
コンパイル時間 2,675 ms
コンパイル使用メモリ 88,948 KB
実行使用メモリ 60,768 KB
最終ジャッジ日時 2024-07-01 22:31:29
合計ジャッジ時間 15,925 ms
ジャッジサーバーID
(参考情報)
judge4 / judge1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 43
権限があれば一括ダウンロードができます

ソースコード

diff #

import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
import java.util.Stack;

public class Main implements Runnable { //Runnableを実装する
    public static void main(String[] args) {
        new Thread(null, new Main(), "", 16 * 1024 * 1024).start(); //16MBスタックを確保して実行
    }
    
    void verify() {
    	Random rnd=new Random();
    	int N=10;
    	int[] a=new int[N];
    	do {
    		for (int i=0;i<N;++i) a[i]=rnd.nextInt(3);
    		if (exact(a) != solve(a)) {
    			tr(exact(a),solve(a),a);
    			break;
    		} else {
    			tr("ok");
    		}
    	} while (true);
    }
    
    
    int exact(int[] a) {
    	int N=a.length;
    	if (N==0) return 0;
    	int ret=Integer.MAX_VALUE/3;
    	for (int  L=0;L<a.length;++L) {
    		int R=L;
    		while (R < N && a[L]==a[R]) ++R;
    		int[] na=new int[N-(R-L)];
    		System.arraycopy(a, 0, na, 0, L);
    		System.arraycopy(a, R, na, L, N-R);
    		ret=Math.min(ret, exact(na)+1);
    	}
    	return ret;
    }
    
    int solve(int[] a) {
		Stack<Integer> stk=new Stack<>();
		int ans=0;
		for (int i=0, j=0; i<a.length; i=j+1) {
			while (j+1<a.length && a[i]==a[j+1]) ++j;
			int v=a[i];
			stk.add(v);
			if (stk.size() >= 2) {
				int x=stk.pop();
				if (x != stk.peek()) stk.add(x);
			}
			if (stk.size() >= 3) {
				int x=stk.pop();
				int y=stk.pop();
				int z=stk.pop();
				if (x==z) {
					ans+=1;
					stk.add(x);
					continue;
				}
				stk.add(z);
				stk.add(y);
				stk.add(x);
			}
		}
		ans+=stk.size() - (stk.size() - 1)/ 3;
		return ans;
    }

    public void run() {
		Scanner sc=new Scanner(System.in);
		PrintWriter pw=new PrintWriter(System.out);
		int N=sc.nextInt();
		char[] cs=sc.next().toCharArray();
		int[] a=new int[N];
		Arrays.setAll(a, i->"RGB".indexOf(cs[i]));
		pw.println(solve(a));
		pw.close();
	}	
	
	void tr(Object ... o) {System.out.println(Arrays.deepToString(o));}
}
0