結果

問題 No.1647 Travel in Mitaru city 2
ユーザー startcpp
提出日時 2021-08-13 23:39:38
言語 C++14
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 181 ms / 2,500 ms
コード長 1,517 bytes
コンパイル時間 745 ms
コンパイル使用メモリ 73,576 KB
実行使用メモリ 28,512 KB
最終ジャッジ日時 2024-10-13 03:24:13
合計ジャッジ時間 10,620 ms
ジャッジサーバーID
(参考情報)
judge3 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 48
権限があれば一括ダウンロードができます

ソースコード

diff #

//O(H + W + N)じゃないので負けた気がするけど、union find解を実装します。
#include <iostream>
#include <vector>
#define rep(i, n) for(i = 0; i < n; i++)
using namespace std;

struct UF {
	int par[200000];
	UF() { for (int i = 0; i < 200000; i++) par[i] = i; }
	int root(int x) { if (par[x] == x) return x; return par[x] = root(par[x]); }
	bool same(int x, int y) { return root(x) == root(y); }
	void merge(int x, int y) { x = root(x); y = root(y); par[x] = y; }
};

int h, w, n;
vector<int> et[200000];
vector<int> ec[200000];
UF uf;

int parent[200000];
int color[200000];
void dfs(int p, int v) {
	parent[v] = p;
	for (int i = 0; i < et[v].size(); i++) {
		int nv = et[v][i];
		if (nv == p) continue;
		color[nv] = ec[v][i];
		dfs(v, nv);
	}
}

vector<int> get_path(int v, int _root) {
	vector<int> path;
	while (v != _root) {
		path.push_back(color[v]);
		v = parent[v];
	}
	return path;
}

void print(vector<int> ans) {
	cout << ans.size() << endl;
	for (int i = 0; i < ans.size(); i++) {
		cout << ans[i] + 1;
		if (i + 1 < ans.size()) cout << " ";
	}
	cout << endl;
}

signed main() {
	int i;
	
	cin >> h >> w >> n;
	rep(i, n) {
		int r, c;
		cin >> r >> c;
		r--; c--;
		if (uf.same(r, c + h)) {
			dfs(-1, c + h);
			vector<int> ans = get_path(r, c + h);
			ans.push_back(i);
			print(ans);
			return 0;
		}
		else {
			uf.merge(r, c + h);
			et[r].push_back(c + h);
			et[c + h].push_back(r);
			ec[r].push_back(i);
			ec[c + h].push_back(i);
		}
	}
	
	cout << -1 << endl;
	return 0;
}
0