結果

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

ソースコード

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) {
	vector<int> path;
	while (v != 0) {
		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, 0);
			vector<int> p1 = get_path(r);
			vector<int> p2 = get_path(c + h);
			vector<int> ans;
			for (int j = 0; j < p1.size(); j++) ans.push_back(p1[j]);
			for (int j = p2.size() - 1; j >= 0; j--) ans.push_back(p2[j]);
			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