1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
| #include <bits/stdc++.h> #define fst first #define snd second #define re register
using namespace std;
typedef pair<int,int> pii; const int N = 2e5 + 10,M = 1010,inf = 1e9 + 10; int n,m; int ty[M][M],p[N],ad[N],d[N]; pii arr[N]; bool vis[N]; vector<int> ans,g[N];
inline int read(){ int r = 0,w = 1; char c = getchar(); while (c < '0' || c > '9'){ if (c == '-') w = -1; c = getchar(); } while (c >= '0' && c <= '9'){ r = (r << 3) + (r << 1) + (c ^ 48); c = getchar(); } return r * w; }
inline void bfs(int s){ fill(d + 1,d + n + 1,inf); fill(vis + 1,vis + n + 1,false); queue<int> q; q.push(s); vis[s] = true; while (!q.empty()){ int u = q.front(); q.pop(); for (int v:g[u]){ if (vis[v]) continue; d[v] = d[u] + 1; vis[v] = true; q.push(v); } } }
int main(){ n = read(); for (re int i = 1;i <= n;i++) ad[p[i] = read()] = i; m = read(); for (re int i = 1;i <= m;i++){ int a,b; a = read(),b = read(); g[a].push_back(b); g[b].push_back(a); arr[i] = {a,b}; ty[a][b] = ty[b][a] = i; } for (re int i = 1;i <= n;i++){ if (i == ad[i]) continue; bfs(i); if (d[ad[i]] == inf) return puts("-1"),0; int u = ad[i]; vector<int> t; while (u != i){ for (int v:g[u]){ if (d[v] + 1 == d[u]){ swap(p[u],p[v]); t.push_back(ty[u][v]); ans.push_back(ty[u][v]); u = v; break; } } } if (t.size() >= 2){ for (re int j = t.size() - 2;~j;j--){ int x = t[j]; swap(p[arr[x].fst],p[arr[x].snd]); ans.push_back(x); } } for (re int j = 1;j <= n;j++) ad[p[j]] = j; } if (ans.size() > 5e5) puts("-1"); else{ printf("%d\n",ans.size()); for (int x:ans) printf("%d ",x); } return 0; }
|