思路:双向搜索
代码:
#include<bits/stdc++.h> using namespace std; #define fi first #define se second #define pi acos(-1.0) #define LL long long //#define mp make_pair #define pb push_back #define ls rt<<1, l, m #define rs rt<<1|1, m+1, r #define ULL unsigned LL #define pll pair<LL, LL> #define pii pair<int, int> #define piii pair<int,pii> #define mem(a, b) memset(a, b, sizeof(a)) #define fio ios::sync_with_stdio(false);cin.tie(0);cout.tie(0); #define fopen freopen("in.txt", "r", stdin);freopen("out.txt", "w", stout); //head int MOD; int u, v, p; map<int, pii>mp; LL q_pow(LL n, LL k) { LL ans = 1; while(k) { if(k&1) ans = (ans * n) % MOD; n = (n*n) % MOD; k >>= 1; } return ans; } void print(int pos1, int pos2, int ty, int tt) { vector<int>vc; if(ty == 1) { int t = pos1; while(t != u) { if(mp[t].fi == 1) { vc.pb(1); t = (t + MOD - 1) % MOD; } else if(mp[t].fi == 2) { t = (t + 1) % MOD; vc.pb(2); } else if(mp[t].fi == 3) { t = q_pow(t, MOD - 2) % MOD; vc.pb(3); } } reverse(vc.begin(), vc.end()); vc.pb(tt); t = pos2; while(t != v) { if(mp[t].fi == 1) { vc.pb(2); t = (t + MOD - 1) % MOD; } else if(mp[t].fi == 2) { t = (t + 1) % MOD; vc.pb(1); } else if(mp[t].fi == 3) { t = q_pow(t, MOD - 2) % MOD; vc.pb(3); } } } else { int t = pos2; while(t != u) { if(mp[t].fi == 1) { vc.pb(1); t = (t + MOD - 1) % MOD; } else if(mp[t].fi == 2) { t = (t + 1) % MOD; vc.pb(2); } else if(mp[t].fi == 3) { t = q_pow(t, MOD - 2) % MOD; vc.pb(3); } } reverse(vc.begin(), vc.end()); if(tt != 3)vc.pb(3-tt); else vc.pb(tt); t = pos1; while(t != v) { if(mp[t].fi == 1) { vc.pb(2); t = (t + MOD - 1) % MOD; } else if(mp[t].fi == 2) { t = (t + 1) % MOD; vc.pb(1); } else if(mp[t].fi == 3) { t = q_pow(t, MOD - 2) % MOD; vc.pb(3); } } } //cout << pos1 << " " << pos2 << " " << ty << endl; printf("%d ", (int)vc.size()); for (int i = 0; i < vc.size(); i++) printf("%d ", vc[i]); } int main() { scanf("%d %d %d", &u, &v, &p); MOD = p; queue<pii>q; if(u == v) return 0*puts("0"); q.push({u, 1}); q.push({v, 2}); mp[u] = {u, 1}; mp[v] = {v, 2}; while(!q.empty()) { pii p = q.front(); q.pop(); int a = (p.fi + 1) % MOD; if(mp.find(a) != mp.end() && mp[a].se != p.se) { print(p.fi, a, p.se, 1); break; } else if(mp.find(a) == mp.end()){ mp[a] = {1, p.se}; q.push({a, p.se}); } a = (p.fi + MOD - 1) % MOD; if(mp.find(a) != mp.end() && mp[a].se != p.se) { print(p.fi, a, p.se, 2); break; } else if(mp.find(a) == mp.end()){ mp[a] = {2, p.se}; q.push({a, p.se}); } a = q_pow(p.fi, MOD - 2) % MOD; if(mp.find(a) != mp.end() && mp[a].se != p.se) { print(p.fi, a, p.se, 3); break; } else if(mp.find(a) == mp.end()){ mp[a] = {3, p.se}; q.push({a, p.se}); } } return 0; }