結果

問題 No.124 門松列(3)
ユーザー data9824data9824
提出日時 2016-02-05 00:34:03
言語 C++11
(gcc 11.4.0)
結果
AC  
実行時間 4 ms / 5,000 ms
コード長 1,754 bytes
コンパイル時間 797 ms
コンパイル使用メモリ 72,708 KB
実行使用メモリ 4,348 KB
最終ジャッジ日時 2023-10-21 19:14:41
合計ジャッジ時間 1,781 ms
ジャッジサーバーID
(参考情報)
judge9 / judge12
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 4 ms
4,348 KB
testcase_01 AC 1 ms
4,348 KB
testcase_02 AC 2 ms
4,348 KB
testcase_03 AC 4 ms
4,348 KB
testcase_04 AC 4 ms
4,348 KB
testcase_05 AC 4 ms
4,348 KB
testcase_06 AC 1 ms
4,348 KB
testcase_07 AC 1 ms
4,348 KB
testcase_08 AC 1 ms
4,348 KB
testcase_09 AC 1 ms
4,348 KB
testcase_10 AC 2 ms
4,348 KB
testcase_11 AC 2 ms
4,348 KB
testcase_12 AC 2 ms
4,348 KB
testcase_13 AC 2 ms
4,348 KB
testcase_14 AC 2 ms
4,348 KB
testcase_15 AC 2 ms
4,348 KB
testcase_16 AC 2 ms
4,348 KB
testcase_17 AC 1 ms
4,348 KB
testcase_18 AC 2 ms
4,348 KB
testcase_19 AC 2 ms
4,348 KB
testcase_20 AC 2 ms
4,348 KB
testcase_21 AC 2 ms
4,348 KB
testcase_22 AC 1 ms
4,348 KB
testcase_23 AC 3 ms
4,348 KB
testcase_24 AC 3 ms
4,348 KB
testcase_25 AC 3 ms
4,348 KB
testcase_26 AC 2 ms
4,348 KB
testcase_27 AC 2 ms
4,348 KB
testcase_28 AC 4 ms
4,348 KB
testcase_29 AC 4 ms
4,348 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <iostream>
#include <vector>
#include <limits>
#include <algorithm>

using namespace std;

struct State {
	int x;
	int y;
	int previousValue;
	int steps;
	State(int x, int y, int previousValue, int steps) :
		x(x), y(y), previousValue(previousValue), steps(steps) {
	}
};

const int dx[] = { 1, -1, 0, 0 };
const int dy[] = { 0, 0, 1, -1 };

bool isKadomatsuSequence(int a, int b, int c) {
	if (a < 0 || b < 0 || c < 0) {
		return true;
	}
	if (a != c) {
		if (a < b && b > c) {
			return true;
		}
		if (a > b && b < c) {
			return true;
		}
	}
	return false;
}

int main() {
	int w, h;
	cin >> w >> h;
	vector<vector<int> > m(w, vector<int>(h));
	for (int y = 0; y < h; ++y) {
		for (int x = 0; x < w; ++x) {
			cin >> m[x][y];
		}
	}
	vector<State> states;
	vector<vector<vector<int> > > shortest(w, vector<vector<int> >(h, vector<int>(4, numeric_limits<int>::max())));
	states.push_back(State(0, 0, -1, 0));
	for (int d = 0; d < 4; ++d) {
		shortest[0][0][d] = states.back().steps;
	}
	while (!states.empty()) {
		State top = states.back();
		states.pop_back();
		int topValue = m[top.x][top.y];
		for (int d = 0; d < 4; ++d) {
			State next(top.x + dx[d], top.y + dy[d], topValue, top.steps + 1);
			if (0 <= next.x && next.x < w 
				&& 0 <= next.y && next.y < h
				&& isKadomatsuSequence(top.previousValue, topValue, m[next.x][next.y])
				&& shortest[next.x][next.y][d] > next.steps) {
				shortest[next.x][next.y][d] = next.steps;
				if (next.x != w - 1 || next.y != h - 1) {
					states.push_back(next);
				}
			}
		}
	}
	int result = numeric_limits<int>::max();
	for (int d = 0; d < 4; ++d) {
		result = min(result, shortest[w - 1][h - 1][d]);
	}
	cout << (result == numeric_limits<int>::max() ? -1 : result) << endl;
	return 0;
}
0