EvbCFfp1XB

problem and my answer.


source code

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Collections;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class StickXorVis {

private static final int minL = 1;
private static final int maxL = 25;

private int N = 60;
private int K = 500;
private int[] L;

private SecureRandom rnd;

private int[][] A;

private long seed;
private int score;

private void generate(String seedStr) {
try {
rnd = SecureRandom.getInstance("SHA1PRNG");
seed = Long.parseLong(seedStr);
rnd.setSeed(seed);

L = new int[K];
for (int i = 0; i < L.length; i++) {
L[i] = rnd.nextInt(maxL - minL + 1) + minL;
}

A = new int[N][N];
for (int r = 0; r < N; r++) {
for (int c = 0; c < N; c++) {
A[r][c] = rnd.nextDouble() < 0.5 ? 0 : 1;
}
}

} catch (Exception e) {
addFatalError("An exception occurred while generating test case.");
e.printStackTrace();
}
}

public double runTest(String seed) {
try {
generate(seed);

if (proc == null) {
return -1;
}

int[][] stickXor;
try {
stickXor = getSolution(N, K, L, A);
} catch (Exception e) {
addFatalError("Failed to get result from getSolution.");
return -1.0;
}

for (int i = 0; i < stickXor.length; i++) {
for (int j = 0; j < stickXor[i].length; j++) {
if (stickXor[i][j] < 0 || stickXor[i][j] >= N) {
addFatalError("You can only make stickXor inside the area.");
return -1.0;
}
}
if (!(stickXor[i][0] == stickXor[i][2] || stickXor[i][1] == stickXor[i][3])) {
addFatalError("stickXor is invalid shape.");
return -1.0;
}
}

int score0 = calculateScore();

score = calculateScore() - score0;

drawer = null;
if (vis) {
drawer = new Drawer();
}

ArrayList<Pair<Integer, Integer>> pairs = new ArrayList<>();
for (int k = 0; k < K; k++) {
pairs.add(new Pair<Integer, Integer>(L[k], k));
}
Collections.sort(pairs);

for (int k = 0; k < K; k++) {
int i = pairs.get(k).second.intValue();
flip(stickXor[i][0], stickXor[i][1], stickXor[i][2], stickXor[i][3]);

if (vis) {

score = calculateScore() - score0;

numSticks = k + 1;

drawer.repaint();
try {
Thread.sleep(100);
} catch (Exception e) {
}
}
}

score = calculateScore() - score0;

return score;

} catch (Exception e) {
addFatalError("An exception occurred while trying to get your program's results.");
e.printStackTrace();
return -1.0;
}
}

private int calculateScore() {
int score = 0;
for (int r = 0; r < N; r++) {
for (int c = 0; c < N; c++) {
if (A[r][c] == 0) {
score++;
}
}
}
return score;
}

private void flip(int startR, int startC, int endR, int endC) {
for (int r = startR; r <= endR; r++) {
for (int c = startC; c <= endC; c++) {
A[r][c] ^= 1;
}
}
}

private static String exec;
private static boolean vis, debug;
private static Process proc;
private InputStream is;
private OutputStream os;
private BufferedReader br;

private int[][] getSolution(int N, int K, int[] L, int[][] A) throws IOException {
StringBuffer sb = new StringBuffer();
sb.append(N).append(" ").append(K).append("\n");
for (int i = 0; i < L.length; ++i) {
sb.append(L[i]).append(" ");
}
sb.append("\n");
for (int i = 0; i < A.length; ++i) {
for (int j = 0; j < A[i].length; ++j) {
sb.append(A[i][j]);
}
sb.append("\n");
}
os.write(sb.toString().getBytes());
os.flush();

int[][] ret = new int[K][4];
for (int i = 0; i < K; i++) {
String[] split = br.readLine().split(" ");
for (int j = 0; j < 4; j++) {
ret[i][j] = Integer.parseInt(split[j]) - 1;
}
}
return ret;
}

public StickXorVis(String seed) {
try {
if (exec != null) {
try {
Runtime rt = Runtime.getRuntime();
proc = rt.exec(exec);
os = proc.getOutputStream();
is = proc.getInputStream();
br = new BufferedReader(new InputStreamReader(is));
new ErrorReader(proc.getErrorStream()).start();
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("Score = " + runTest(seed));
stopSolution();
} catch (Exception e) {
e.printStackTrace();
}
}

private void stopSolution() {
if (proc != null) {
try {
proc.destroy();
} catch (Exception e) {
e.printStackTrace();
}
}
}

private Drawer drawer;
private int numSticks;

class Drawer extends JFrame {
public static final int EXTRA_WIDTH = 300;
public static final int EXTRA_HEIGHT = 30;

public DrawerPanel panel;

public int cellSize, boardSize;
public int width, height;

class DrawerPanel extends JPanel {

public void paint(Graphics g) {

BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = (Graphics2D) bi.getGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

g2.setColor(Color.LIGHT_GRAY);
g2.fillRect(0, 0, width, height);

for (int r = 0; r < N; r++) {
for (int c = 0; c < N; c++) {
if (A[r][c] == 0) {
g2.setColor(Color.WHITE);
} else {
g2.setColor(Color.BLACK);
}
g2.fillRect(15 + cellSize * c, 15 + cellSize * r, cellSize, cellSize);
}
}

g2.setColor(Color.BLUE);
for (int i = 0; i <= boardSize; i++) {
g2.drawLine(15 + i * cellSize, 15, 15 + i * cellSize, 15 + cellSize * boardSize);
g2.drawLine(15, 15 + i * cellSize, 15 + cellSize * boardSize, 15 + i * cellSize);
}

g2.setColor(Color.BLACK);
g2.setFont(new Font("Arial", Font.BOLD, 12));

int x = 40 + boardSize * cellSize;
int y = 30;

g2.drawString("Seed : " + seed, x, y += 15);
g2.drawString("numRectangles : " + (numSticks + "/" + 500), x, y += 15);
g2.drawString("Score : " + score, x, y += 15);

g.drawImage(bi, 0, 0, width, height, null);
}
}

class DrawerWindowListener extends WindowAdapter {
public void windowClosing(WindowEvent event) {
stopSolution();
System.exit(0);
}
}

public Drawer() {
super();

panel = new DrawerPanel();
getContentPane().add(panel);

addWindowListener(new DrawerWindowListener());

boardSize = N;
this.cellSize = 8;
width = cellSize * boardSize + EXTRA_WIDTH;
height = cellSize * boardSize + EXTRA_HEIGHT;
setSize(width, height);

setTitle("Visualizer tool for problem Stick Xor");

setResizable(false);
setVisible(true);
}
}

public static void main(String[] args) {
String seed = "1";
vis = true;
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-seed"))
seed = args[++i];
if (args[i].equals("-exec"))
exec = args[++i];
if (args[i].equals("-novis"))
vis = false;
if (args[i].equals("-debug"))
debug = true;
}
new StickXorVis(seed);
}

void addFatalError(String message) {
System.out.println(message);
}
}

class ErrorReader extends Thread {
BufferedReader error;

public ErrorReader(InputStream is) {
error = new BufferedReader(new InputStreamReader(is));
}

public void run() {
try {
for (String s; (s = error.readLine()) != null;) {
System.err.println(s);
System.err.flush();
}
} catch (Exception e) {
e.getStackTrace();
}
}
}

class Pair<T extends Comparable<T>, S> implements Comparable<Pair<T, S>> {
public T first;
public S second;

public Pair(T t, S s) {
this.first = t;
this.second = s;
}

private int hash = 0;

@Override
public int hashCode() {
if (hash == 0) {
final int prime = 31;
int result = 1;
result = prime * result + ((first == null) ? 0 : first.hashCode());
result = prime * result + ((second == null) ? 0 : second.hashCode());
hash = result;
}
return hash;
}

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Pair<T, S> other = (Pair<T, S>) obj;
if (first == null) {
if (other.first != null)
return false;
} else if (!first.equals(other.first))
return false;
if (second == null) {
if (other.second != null)
return false;
} else if (!second.equals(other.second))
return false;
return true;
}

@Override
public int compareTo(Pair<T, S> o) {
return first.compareTo(o.first);
}
}



Screenshot-2018-6-4 ATS ( ats5515) Twitter
”例の挿入、削除、ランダム取得がO(1)のset” を実装してみた。

source code

class IntSet {
private static final int EMPTY = -1;
private int size;
private int[] indexToValue;
private int[] valueToIndex;

public IntSet(int capacity) {
this.size = 0;
indexToValue = new int[capacity];
valueToIndex = new int[capacity];
Arrays.fill(valueToIndex, EMPTY);
}

public boolean add(int value) {
if (valueToIndex[value] != EMPTY) {
return false;
}
indexToValue[size] = value;
valueToIndex[indexToValue[size]] = size;
size++;
return true;
}

public boolean remove(int index) {
if (size == 0) {
return false;
}
assert index < size;
int swap = indexToValue[index];
indexToValue[index] = indexToValue[size - 1];
indexToValue[size - 1] = swap;

valueToIndex[indexToValue[index]] = index;
valueToIndex[indexToValue[size - 1]] = EMPTY;

size--;
return true;
}

public boolean removeValue(int value) {
int index = indexOf(value);
if (index == EMPTY) {
return false;
}
remove(index);
return true;
}

public int get(int index) {
assert index < size;
return indexToValue[index];
}

public int indexOf(int value) {
return valueToIndex[value];
}

public int size() {
return size;
}

public boolean isEmpty() {
return size() <= 0;
}

public void clear() {
for (; size() > 0;) {
remove(0);
}
}

public boolean contains(int value) {
return indexOf(value) != EMPTY;
}

}




Approach SA(1 case あたり 約1550点)

近傍
  • 1つずらす(縦長だったら上、下両方試していい方へ移動) (遷移確率5%)
  • ランダムに形と位置を変える(遷移確率47.5%)
  • 2つのstickを入れ替える(遷移確率47.5%)

Greedy (約1230点)

  • L[k]の長いkから決める
  • 全探索して最もスコアが良くなる位置、形を選ぶ

Greedy (約1330点)

  • L[k]の長いkから決める
  • 全探索して最もスコアが良くなる位置、形を選ぶ
  • stickの端点と外の点が違う色になる時に減点する

感想

  • SAって1秒でもうまくいくんだなーと思った。
  • assert 文も実行される仕様になかなか気づかなかった。

追記
Approach
SA(約1600)
  • 1つずらす(縦長だったら上、下両方試していい方へ移動ではなく、片方決めうちのほうが精度が良かった)(確率0%(精度は良くなったけど必要なかった))
  • ランダムに形と位置を変える(確率15%)
  • 長さが1違う2つのstickを入れ替える(確率85%)
  • https://yukicoder.me/submissions/262524


source code



import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;

public class Main {
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {

String line = br.readLine();
String[] split = line.split(" ");
int N = Integer.parseInt(split[0]);
int K = Integer.parseInt(split[1]);

line = br.readLine();
split = line.split(" ");
int[] L = new int[K];
for (int i = 0; i < K; i++) {
L[i] = Integer.parseInt(split[i]);
}

int[][] A = new int[N][N];
for (int r = 0; r < N; r++) {
line = br.readLine();
for (int c = 0; c < N; c++) {
A[r][c] = line.charAt(c) - '0';
}
}

String ret = new Main().run(N, K, L, A);
System.out.println(ret);
System.out.flush();
} catch (Exception e) {
e.printStackTrace();
}
}

private double score;
private double bestScore;
static final Watch watch = new Watch();
static final XorShift rng = new XorShift(System.nanoTime());
private SAState sa = new SAState();
private int N;
private int K;
private int[] L;
private int[][] A;
private int W0;
private boolean[] isVerticals;
private int[] rs;
private int[] cs;
private boolean[] bestIsVerticals;
private int[] bestRs;
private int[] bestCs;

private String run(int N, int K, int[] L, int[][] A) {
init(N, K, L, A);
greedy();
SA();
return makeSolution();
}

private void init(int n, int k, int[] l, int[][] a) {

N = n;
K = k;
L = l;
A = a;

isVerticals = new boolean[K];
rs = new int[K];
cs = new int[K];

bestIsVerticals = new boolean[K];
bestRs = new int[K];
bestCs = new int[K];

W0 = 0;
W0 = calculateScore(a);

Utils.debug("init", "time", watch.getSecondString());
}

private void greedy() {
for (int k = 0; k < K; k++) {
isVerticals[k] = rng.nextDouble() < 0.5;
if (isVerticals[k]) {
rs[k] = (int) ((N - L[k]) * rng.nextDouble());
cs[k] = (int) (N * rng.nextDouble());
} else {
rs[k] = (int) (N * rng.nextDouble());
cs[k] = (int) ((N - L[k]) * rng.nextDouble());
}

flip(k, isVerticals[k], rs[k], cs[k]);
}
}

private void SA() {
score = calculateScore(A);
bestScore = -1e99;
saveBest();

sa.startTime = watch.getSecond();
sa.endTime = 0.85;
sa.init();
for (;; sa.numIterations++) {
if ((sa.numIterations & ((1 << 10) - 1)) == 0) {
sa.update();

if (sa.isTLE()) {
loadBest();
Utils.debug(sa.numIterations, String.format("%.2f%%", 100.0 * sa.validIterations / sa.numIterations), String.format("%.2f%%", 100.0 * sa.acceptIterations / sa.validIterations), String.format("%7.2f", score), String.format("%7.2f", bestScore), String.format("%.6f", 1.0 / sa.inverseTemperature), String.format("%.6f", 1.0 / sa.lastAcceptTemperature));
break;
}
}

mutate();
}
Utils.debug("SA", "time", watch.getSecondString());
}

private void mutate() {
int random = (int) (100 * rng.nextDouble());
if (random < 5) {
move();
} else if (random < 52) {
random();
} else {
swap();
}
}

private void random() {
int k = (int) (K * rng.nextDouble());

boolean currentIsVertical = isVerticals[k];
int currentR = rs[k];
int currentC = cs[k];

boolean newIsVertical = rng.nextDouble() < 0.5;
int newR = currentR + (int) (-sa.range * 0.5 + sa.range * rng.nextDouble());
int newC = currentC + (int) (-sa.range * 0.5 + sa.range * rng.nextDouble());
if (newIsVertical) {
newR = Math.min(Math.max(newR, 0), N - L[k] - 1);
newC = Math.min(Math.max(newC, 0), N - 1);
} else {
newR = Math.min(Math.max(newR, 0), N - 1);
newC = Math.min(Math.max(newC, 0), N - L[k] - 1);
}
double deltaScore = 0;

if (currentIsVertical) {
for (int l = 0; l < L[k]; l++) {
if (A[currentR + l][currentC] == 0) {
deltaScore--;
} else {
deltaScore++;
}
}
} else {
for (int l = 0; l < L[k]; l++) {
if (A[currentR][currentC + l] == 0) {
deltaScore--;
} else {
deltaScore++;
}
}
}
if (newIsVertical) {
for (int l = 0; l < L[k]; l++) {
if (isIntersect(newR + l, newC, currentR, currentC, currentR + (currentIsVertical ? L[k] - 1 : 0), currentC + (currentIsVertical ? 0 : L[k] - 1))) {
if (A[newR + l][newC] == 0) {
deltaScore++;
} else {
deltaScore--;
}
} else {
if (A[newR + l][newC] == 1) {
deltaScore++;
} else {
deltaScore--;
}
}
}
} else {
for (int l = 0; l < L[k]; l++) {
if (isIntersect(newR, newC + l, currentR, currentC, currentR + (currentIsVertical ? L[k] - 1 : 0), currentC + (currentIsVertical ? 0 : L[k] - 1))) {
if (A[newR][newC + l] == 0) {
deltaScore++;
} else {
deltaScore--;
}
} else {
if (A[newR][newC + l] == 1) {
deltaScore++;
} else {
deltaScore--;
}
}
}
}

if (sa.accept(deltaScore)) {
score += deltaScore;

flip(k, currentIsVertical, currentR, currentC);
flip(k, newIsVertical, newR, newC);

isVerticals[k] = newIsVertical;
rs[k] = newR;
cs[k] = newC;

saveBest();
} else {
}
}

private void swap() {
int k = (int) (K * rng.nextDouble());
int k2 = (int) (K * rng.nextDouble());
while (L[k] == L[k2] || Math.abs(L[k] - L[k2]) > 5) {
k2 = (int) (K * rng.nextDouble());
}

if (L[k] > L[k2]) {
if (isVerticals[k2]) {
if (rs[k2] + L[k] >= N) {
return;
}
} else {
if (cs[k2] + L[k] >= N) {
return;
}
}
} else {
if (isVerticals[k]) {
if (rs[k] + L[k2] >= N) {
return;
}
} else {
if (cs[k] + L[k2] >= N) {
return;
}
}
}
double deltaScore = 0;

if (L[k] > L[k2]) {
if (isVerticals[k]) {
for (int l = L[k2]; l < L[k]; l++) {
if (A[rs[k] + l][cs[k]] == 0) {
deltaScore--;
} else {
deltaScore++;
}
}
} else {
for (int l = L[k2]; l < L[k]; l++) {
if (A[rs[k]][cs[k] + l] == 0) {
deltaScore--;
} else {
deltaScore++;
}
}
}

if (isVerticals[k2]) {
for (int l = L[k2]; l < L[k]; l++) {
if (isIntersect(rs[k2] + l, cs[k2], rs[k] + (isVerticals[k] ? L[k2] : 0), cs[k] + (isVerticals[k] ? 0 : L[k2]), rs[k] + (isVerticals[k] ? L[k] - 1 : 0), cs[k] + (isVerticals[k] ? 0 : L[k] - 1))) {
if (A[rs[k2] + l][cs[k2]] == 1) {
deltaScore--;
} else {
deltaScore++;
}
} else {
if (A[rs[k2] + l][cs[k2]] == 0) {
deltaScore--;
} else {
deltaScore++;
}
}
}
} else {
for (int l = L[k2]; l < L[k]; l++) {
if (isIntersect(rs[k2], cs[k2] + l, rs[k] + (isVerticals[k] ? L[k2] : 0), cs[k] + (isVerticals[k] ? 0 : L[k2]), rs[k] + (isVerticals[k] ? L[k] - 1 : 0), cs[k] + (isVerticals[k] ? 0 : L[k] - 1))) {
if (A[rs[k2]][cs[k2] + l] == 1) {
deltaScore--;
} else {
deltaScore++;
}
} else {
if (A[rs[k2]][cs[k2] + l] == 0) {
deltaScore--;
} else {
deltaScore++;
}
}
}
}
} else {
if (isVerticals[k]) {
for (int l = L[k]; l < L[k2]; l++) {
if (A[rs[k] + l][cs[k]] == 0) {
deltaScore--;
} else {
deltaScore++;
}
}
} else {
for (int l = L[k]; l < L[k2]; l++) {
if (A[rs[k]][cs[k] + l] == 0) {
deltaScore--;
} else {
deltaScore++;
}
}
}

if (isVerticals[k2]) {
for (int l = L[k]; l < L[k2]; l++) {
if (isIntersect(rs[k2] + l, cs[k2], rs[k] + (isVerticals[k] ? L[k] : 0), cs[k] + (isVerticals[k] ? 0 : L[k]), rs[k] + (isVerticals[k] ? L[k2] - 1 : 0), cs[k] + (isVerticals[k] ? 0 : L[k2] - 1))) {
if (A[rs[k2] + l][cs[k2]] == 1) {
deltaScore--;
} else {
deltaScore++;
}
} else {
if (A[rs[k2] + l][cs[k2]] == 0) {
deltaScore--;
} else {
deltaScore++;
}
}
}
} else {
for (int l = L[k]; l < L[k2]; l++) {
if (isIntersect(rs[k2], cs[k2] + l, rs[k] + (isVerticals[k] ? L[k] : 0), cs[k] + (isVerticals[k] ? 0 : L[k]), rs[k] + (isVerticals[k] ? L[k2] - 1 : 0), cs[k] + (isVerticals[k] ? 0 : L[k2] - 1))) {
if (A[rs[k2]][cs[k2] + l] == 1) {
deltaScore--;
} else {
deltaScore++;
}
} else {
if (A[rs[k2]][cs[k2] + l] == 0) {
deltaScore--;
} else {
deltaScore++;
}
}
}
}
}
if (sa.accept(deltaScore)) {
score += deltaScore;
if (L[k] > L[k2]) {
if (isVerticals[k]) {
for (int l = L[k2]; l < L[k]; l++) {
A[rs[k] + l][cs[k]] ^= 1;
}
} else {
for (int l = L[k2]; l < L[k]; l++) {
A[rs[k]][cs[k] + l] ^= 1;
}
}

if (isVerticals[k2]) {
for (int l = L[k2]; l < L[k]; l++) {
A[rs[k2] + l][cs[k2]] ^= 1;
}
} else {
for (int l = L[k2]; l < L[k]; l++) {
A[rs[k2]][cs[k2] + l] ^= 1;
}
}
} else {
if (isVerticals[k]) {
for (int l = L[k]; l < L[k2]; l++) {
A[rs[k] + l][cs[k]] ^= 1;
}
} else {
for (int l = L[k]; l < L[k2]; l++) {
A[rs[k]][cs[k] + l] ^= 1;
}
}

if (isVerticals[k2]) {
for (int l = L[k]; l < L[k2]; l++) {
A[rs[k2] + l][cs[k2]] ^= 1;
}
} else {
for (int l = L[k]; l < L[k2]; l++) {
A[rs[k2]][cs[k2] + l] ^= 1;
}
}
}

{
boolean swap = isVerticals[k];
isVerticals[k] = isVerticals[k2];
isVerticals[k2] = swap;
}
{
int swap = rs[k];
rs[k] = rs[k2];
rs[k2] = swap;
swap = cs[k];
cs[k] = cs[k2];
cs[k2] = swap;
}
saveBest();
} else {
}
}

private void move() {
int k = (int) (K * rng.nextDouble());

double deltaScoreRorD = 0;

if (isVerticals[k]) {
if (rs[k] + L[k] >= N) {
deltaScoreRorD = Double.NEGATIVE_INFINITY;
}
} else {
if (cs[k] + L[k] >= N) {
deltaScoreRorD = Double.NEGATIVE_INFINITY;
}
}

if (deltaScoreRorD > -1) {
if (A[rs[k]][cs[k]] == 0) {
deltaScoreRorD--;
} else {
deltaScoreRorD++;
}
if (isVerticals[k]) {
if (A[rs[k] + L[k]][cs[k]] == 0) {
deltaScoreRorD--;
} else {
deltaScoreRorD++;
}
} else {
if (A[rs[k]][cs[k] + L[k]] == 0) {
deltaScoreRorD--;
} else {
deltaScoreRorD++;
}
}
}

double deltaScoreLorU = 0;

if (isVerticals[k]) {
if (rs[k] - 1 < 0) {
deltaScoreLorU = Double.NEGATIVE_INFINITY;
}
} else {
if (cs[k] - 1 < 0) {
deltaScoreLorU = Double.NEGATIVE_INFINITY;
}
}

if (deltaScoreLorU > -1) {
if (isVerticals[k]) {
if (A[rs[k] - 1][cs[k]] == 0) {
deltaScoreLorU--;
} else {
deltaScoreLorU++;
}
if (A[rs[k] + L[k] - 1][cs[k]] == 0) {
deltaScoreLorU--;
} else {
deltaScoreLorU++;
}
} else {
if (A[rs[k]][cs[k] - 1] == 0) {
deltaScoreLorU--;
} else {
deltaScoreLorU++;
}
if (A[rs[k]][cs[k] + L[k] - 1] == 0) {
deltaScoreLorU--;
} else {
deltaScoreLorU++;
}
}
}

double deltaScore = Math.max(deltaScoreRorD, deltaScoreLorU);

if (sa.accept(deltaScore)) {
score += deltaScore;
if (deltaScoreRorD > deltaScoreLorU) {
if (isVerticals[k]) {
A[rs[k]][cs[k]] ^= 1;
A[rs[k] + L[k]][cs[k]] ^= 1;
rs[k]++;
} else {
A[rs[k]][cs[k]] ^= 1;
A[rs[k]][cs[k] + L[k]] ^= 1;
cs[k]++;
}
} else {
if (isVerticals[k]) {
A[rs[k] - 1][cs[k]] ^= 1;
A[rs[k] + L[k] - 1][cs[k]] ^= 1;
rs[k]--;
} else {
A[rs[k]][cs[k] - 1] ^= 1;
A[rs[k]][cs[k] + L[k] - 1] ^= 1;
cs[k]--;
}
}
saveBest();
} else {
}
}

private String makeSolution() {
StringBuilder result = new StringBuilder();
for (int k = 0; k < K; k++) {
if (isVerticals[k]) {
result.append("" + (rs[k] + 1) + " " + (cs[k] + 1) + " " + (rs[k] + 1 + (L[k] - 1)) + " " + (cs[k] + 1) + "\\n");
} else {
result.append("" + (rs[k] + 1) + " " + (cs[k] + 1) + " " + (rs[k] + 1) + " " + (cs[k] + 1 + (L[k] - 1)) + "\\n");
}
}
return result.toString();
}

private boolean isIntersect(int r, int c, int minR, int minC, int maxR, int maxC) {
return r >= minR && r <= maxR && c >= minC && c <= maxC;
}

private void flip(int k, boolean isVertical, int r, int c) {
if (isVertical) {
for (int l = 0; l < L[k]; l++) {
A[r + l][c] ^= 1;
}
} else {
for (int l = 0; l < L[k]; l++) {
A[r][c + l] ^= 1;
}
}
}

private int calculateScore(int[][] a) {
int W = 0;
for (int r = 0; r < N; r++) {
for (int c = 0; c < N; c++) {
if (a[r][c] == 0) {
W++;
}
}
}
return W - W0;
}

private void saveBest() {
if (score > bestScore) {
bestScore = score;
for (int k = 0; k < K; k++) {
bestIsVerticals[k] = isVerticals[k];
bestRs[k] = rs[k];
bestCs[k] = cs[k];
}
}
}

private void loadBest() {
score = bestScore;
for (int k = 0; k < K; k++) {
isVerticals[k] = bestIsVerticals[k];
rs[k] = bestRs[k];
cs[k] = bestCs[k];
}
}
}

class SAState {

public static final boolean useTime = true;

public double startTime = 0;
public double endTime = 9.5;
public double time = startTime;

public double startTemperature = 1;
public double endTemperature = 0;
public double inverseTemperature = 1.0 / startTemperature;
public double lastAcceptTemperature = startTemperature;
public double startRange = 31;
public double endRange = 3;
public double range = startRange;

public int numIterations;
public int validIterations;
public int acceptIterations;

public void init() {
numIterations = 0;
validIterations = 0;
acceptIterations = 0;

startTime = useTime ? Main.watch.getSecond() : numIterations;

update();
lastAcceptTemperature = inverseTemperature;
}

public void update() {
updateTime();
updateTemperature();
updateRange();
}

public void updateTemperature() {
inverseTemperature = 1.0 / (endTemperature + (startTemperature - endTemperature) * Math.pow((endTime - time) / (endTime - startTime), 1.0));
}

public void updateRange() {
range = endRange + (startRange - endRange) * Math.pow((endTime - time) / (endTime - startTime), 1.0);
}

public void updateTime() {
time = useTime ? Main.watch.getSecond() : numIterations;
}

public boolean isTLE() {
return time >= endTime;
}

public boolean accept(double deltaScore) {
return acceptB(deltaScore);
}

public boolean acceptB(double deltaScore) {
validIterations++;

if (deltaScore > -1e-9) {
acceptIterations++;
return true;
}

assert deltaScore < 0;
assert 1.0 / inverseTemperature >= 0;

if (deltaScore * inverseTemperature < -10) {
return false;
}

if (Main.rng.nextDouble() < Math.exp(deltaScore * inverseTemperature)) {
acceptIterations++;
lastAcceptTemperature = inverseTemperature;
return true;
}
return false;
}

public boolean acceptS(double deltaScore) {
validIterations++;

if (deltaScore < 1e-9) {
acceptIterations++;
return true;
}

assert deltaScore > 0;
assert 1.0 / inverseTemperature >= 0;

if (-deltaScore * inverseTemperature < -10) {
return false;
}

if (Main.rng.nextDouble() < Math.exp(-deltaScore * inverseTemperature)) {
acceptIterations++;
lastAcceptTemperature = inverseTemperature;
return true;
}
return false;
}

}

final class Utils {
private Utils() {
}

public static final void debug(Object... o) {
System.err.println(toString(o));
}

public static final String toString(Object... o) {
return Arrays.deepToString(o);
}

}

class Watch {
private long start;

public Watch() {
init();
}

public double getSecond() {
return (System.nanoTime() - start) * 1e-9;
}

public void init() {
init(System.nanoTime());
}

private void init(long start) {
this.start = start;
}

public String getSecondString() {
return toString(getSecond());
}

public static final String toString(double second) {
if (second < 60) {
return String.format("%5.2fs", second);
} else if (second < 60 * 60) {
int minute = (int) (second / 60);
return String.format("%2dm%2ds", minute, (int) (second % 60));
} else {
int hour = (int) (second / (60 * 60));
int minute = (int) (second / 60);
return String.format("%2dh%2dm%2ds", hour, minute % (60), (int) (second % 60));
}
}

}

class XorShift {
private int w = 88675123;
private int x = 123456789;
private int y = 362436069;
private int z = 521288629;

public XorShift(long l) {
x = (int) l;
}

public int nextInt() {
final int t = x ^ (x << 11);
x = y;
y = z;
z = w;
w = w ^ (w >>> 19) ^ (t ^ (t >>> 8));
return w;
}

public long nextLong() {
return ((long) nextInt() << 32) ^ (long) nextInt();
}

public double nextDouble() {
return (nextInt() >>> 1) * 4.6566128730773926E-10;
}

public int nextInt(int n) {
return (int) (n * nextDouble());
}

}


このページのトップヘ