tookunn’s diary

主に競技プログラミング関係

Codeforces #356 Div2 C

問題文

codeforces.com

リアクティブ方式。

考察

最初は素数を使って割り切れるかどうか試していこうと思いましたが、[2,100]での素数の数が25個なので、97,89などの素数がhidden numberだと20クエリ以内に収まらない。

よく考えると,エストラネスのふるい等を使って、47までの素数を見ていって、そこまででhidden numberを割り切れる素数が無ければ、48以上の残っている数は素数だということが分かるので、制限クエリ以内に収まる。

ソースコード

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.NoSuchElementException;

public class Main {
	public void solve() {

		boolean[] used = new boolean[100 + 1];
		boolean[] isPrime = new boolean[100 + 1];

		for(int i = 2;i <= 100;i++){
			boolean f = true;
			for(int j = 2;j * j <= i;j++){
				if(i % j == 0){
					f = false;
				}
			}
			if(f){
				isPrime[i] = true;
			}
		}

		boolean isDiv = false;
		int p = 2;
		for(int i = 0;i < 20;i++){

			while(p <= 100 && used[p]){
				p++;
			}

			out.println(p);
			out.flush();
			String s = next();
			if(s.equals("yes")){
				if(isDiv){
					out.println("composite");
					out.flush();
					return;
				}else{
					isDiv = true;
					used[p] = true;
					for(int j = p + 1;j <= 100;j++){
						if(!isPrime[j] && j % p != 0){
							used[j] = true;
						}
					}
				}
			}else{
				for(int j = p;j <= 100;j += p){
					used[j] = true;
				}
			}
		}
		out.println("prime");
		out.flush();
	}

	public static void main(String[] args) {
		out.flush();
		new Main().solve();
		out.close();
	}

	/* Input */
	private static final InputStream in = System.in;
	private static final PrintWriter out = new PrintWriter(System.out);
	private final byte[] buffer = new byte[2048];
	private int p = 0;
	private int buflen = 0;

	private boolean hasNextByte() {
		if (p < buflen)
			return true;
		p = 0;
		try {
			buflen = in.read(buffer);
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (buflen <= 0)
			return false;
		return true;
	}

	public boolean hasNext() {
		while (hasNextByte() && !isPrint(buffer[p])) {
			p++;
		}
		return hasNextByte();
	}

	private boolean isPrint(int ch) {
		if (ch >= '!' && ch <= '~')
			return true;
		return false;
	}

	private int nextByte() {
		if (!hasNextByte())
			return -1;
		return buffer[p++];
	}

	public String next() {
		if (!hasNext())
			throw new NoSuchElementException();
		StringBuilder sb = new StringBuilder();
		int b = -1;
		while (isPrint((b = nextByte()))) {
			sb.appendCodePoint(b);
		}
		return sb.toString();
	}

	public int nextInt() {
		return Integer.parseInt(next());
	}

	public long nextLong() {
		return Long.parseLong(next());
	}

	public double nextDouble() {
		return Double.parseDouble(next());
	}
}

コンテスト終了直前に解法が下りてきた...もっと早く思いつければよかった。