题解:CF995E Number Clicker
Aurelia_Veil · · 题解
题解:CF995E Number Clicker
刚开始打暴力,发现过不了就写双向 BFS,结果过了,不是,难道不会超时吗,后来才发现是生日悖论。
所以我就是打暴力过的。
首先,原本双向 BFS 是
但是我们看操作 3,它就是求了个逆元,逆元这东西没啥明显的规律,假设它是随机的,我们可以根据生日悖论,发现大概
其次,操作 1 和操作 2 是互逆的,操作 3 因为是逆元,所以也是互逆的,因此可以使用双向 BFS。
双向 BFS 就是基本上就是模板,然后存储了答案序列,记得如果是反向操作 1 和操作 2 要反过来,就没什么重要的点了。
代码如下:
#include<bits/stdc++.h>
using namespace std;
#define int long long
int n,m,p;
int poww(int x,int y){
int base=x;
long long ans=1;
while(y){
if(y&1){
ans*=base;
ans=(ans%p+p)%p;
}
base*=base;
base%=p;
y>>=1;
}
return ans;
}
map<long long,int>k;//存储操作步数
map<long long,int>f;//标记
map<long long,string>aaans;//存储答案
void bfs(int bx,int ex){
queue<pair<int,int>>q;
queue<string>ans;
q.push(make_pair(bx,1));
q.push(make_pair(ex,2));
k[bx]=0;
k[ex]=0;
f[bx]=1;
f[ex]=2;
ans.push("");
ans.push("");
while(!q.empty()){
int u=q.front().first;
int col=q.front().second;
string s=ans.front();
q.pop();
ans.pop();
if(k[u]*2>200){
return;
}
for(int i=1;i<=3;i++){
int v;
if(col==1){
if(i==1){
v=(u+1)%p;
}else if(i==2){
v=(u-1+p)%p;
}else{
v=poww(u,p-2);
}
}else{
if(i==1){
v=(u-1+p)%p;
}else if(i==2){
v=(u+1)%p;
}else{
v=poww(u,p-2);
}
}
if(i==3&&u!=0&&v==0){
continue;
}
if(f.count(v)){
if(f[v]==col){
continue;
}
if(f[v]==3-col){
string hh="";
if(col==1){
hh=s+char(i+'0');
hh=hh+aaans[v];
}else{
hh=char(i+'0')+s;
hh=aaans[v]+hh;
}
#undef int
printf("%d\n",int(hh.length()));
for(int j=0;j<int(hh.length());j++){
printf("%c ",hh[j]);
}
#define int long long
return;
}
}
k[v]=k[u]+1;
f[v]=col;
q.push(make_pair(v,col));
if(col==1){
aaans[v]=s+char(i+'0');
ans.push(s+char(i+'0'));
}else{
aaans[v]=char(i+'0')+s;
ans.push(char(i+'0')+s);
}
}
}
}
signed main(){
scanf("%lld%lld%lld",&n,&m,&p);
if(n==m){//特判
printf("0\n");
return 0;
}
bfs(n,m);
return 0;
}