結果
問題 | No.1647 Travel in Mitaru city 2 |
ユーザー | tko919 |
提出日時 | 2021-08-24 00:19:04 |
言語 | C++17 (gcc 13.3.0 + boost 1.87.0) |
結果 |
AC
|
実行時間 | 144 ms / 2,500 ms |
コード長 | 2,310 bytes |
コンパイル時間 | 2,456 ms |
コンパイル使用メモリ | 208,068 KB |
最終ジャッジ日時 | 2025-01-24 01:42:30 |
ジャッジサーバーID (参考情報) |
judge1 / judge2 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 3 |
other | AC * 48 |
ソースコード
#define _USE_MATH_DEFINES #include <bits/stdc++.h> using namespace std; //template #define rep(i,a,b) for(int i=(int)(a);i<(int)(b);i++) #define ALL(v) (v).begin(),(v).end() using ll=long long int; const int inf = 0x3fffffff; const ll INF = 0x1fffffffffffffff; const double eps=1e-12; template<typename T>inline bool chmax(T& a,T b){if(a<b){a=b;return 1;}return 0;} template<typename T>inline bool chmin(T& a,T b){if(a>b){a=b;return 1;}return 0;} struct UnionFind{ vector<int> par; int n; UnionFind(){} UnionFind(int _n):par(_n,-1),n(_n){} int root(int x){return par[x]<0?x:par[x]=root(par[x]);} bool same(int x,int y){return root(x)==root(y);} int size(int x){return -par[root(x)];} bool unite(int x,int y){ x=root(x),y=root(y); if(x==y)return false; if(size(x)>size(y))swap(x,y); par[y]+=par[x]; par[x]=y; n--; return true; } }; using P=pair<int,int>; vector<P> g[201010]; bool dfs(int v,int p,int tar,vector<int>& path){ if(v==tar)return true; for(auto& [to,id]:g[v])if(to!=p){ path.push_back(id); if(dfs(to,v,tar,path))return true; path.pop_back(); } return false; } int main(){ int h,w,n; cin>>h>>w>>n; vector<int> x(n),y(n); rep(i,0,n){ cin>>x[i]>>y[i]; x[i]--; y[i]--; } UnionFind uni(h+w); rep(i,0,n){ if(uni.unite(x[i],y[i]+h)){ g[x[i]].push_back({y[i]+h,i}); g[y[i]+h].push_back({x[i],i}); } else{ vector<int> res,add; int rt=uni.root(x[i]); dfs(rt,-1,x[i],res); dfs(rt,-1,y[i]+h,add); reverse(ALL(res)); res.insert(res.end(),ALL(add)); if(x[i]!=x[res.front()]){ reverse(ALL(res)); res.push_back(i); reverse(ALL(res)); } else res.push_back(i); stack<int> st; rep(i,0,res.size()){ if(!st.empty() and st.top()==res[i])st.pop(); else st.push(res[i]); } res.clear(); while(!st.empty()){ res.push_back(st.top()); st.pop(); } reverse(ALL(res)); cout<<res.size()<<'\n'; rep(j,0,res.size())cout<<res[j]+1<<(j==res.size()-1?'\n':' '); return 0; } } puts("-1"); return 0; }