求调
查看原帖
求调
1392775
xiejinghan楼主2025/7/21 20:49
#include<bits/stdc++.h>
using namespace std;
int n;
map<long long,int> m;
struct node{
    int x[20],step,kind;
}t;
void turn(int a[],int k){
    int rem[20];
    for(int i=1;i<=k;i++) rem[k-i+1]=a[i];
    for(int i=1;i<=k;i++) a[i]=rem[i];
    return ;
}
long long num(int a[]){
    int s=0;
    for(int i=1;i<=n;i++){
        s=s*10+a[i];
    }
    return s;
}
void bfs(node a,node b){
    queue<node> q;
    q.push(a);q.push(b);
    while(!q.empty()){
        t=a=q.front();
        q.pop();
        for(int i=1;i<=n;i++){
            turn(a.x,i);
            long long h=num(a.x);
            //cout<<h<<endl;
            if(h==num(b.x)&&a.step<1000){
                cout<<a.step+1<<endl;
                return ;
            }
            if(!m[h]){
                m[h]=++a.step;
                q.push(a);
                a.step--;
            }else if(m[h]!=-1&&((a.kind&&m[h]<1000)||(a.kind==0&&m[h]>1000))){
                cout<<a.step+1+m[h]-1000;
                return ;
            }
            a=t;
        }
    }
    return ;
}
int main(){
    cin>>n;
    node a,b;
    int sum=0;
    for(int i=1;i<=n;i++){
        cin>>a.x[i];
        b.x[i]=i;
        if(a.x[i]==b.x[i]) sum++;
    }
    if(sum==n){
        cout<<0<<endl;
        return 0;
    }
    a.step=0,a.kind=0;
    b.step=1000,b.kind=1;
    m[num(a.x)]=-1,m[num(b.x)]=-1;
    bfs(a,b);
    return 0;
}
2025/7/21 20:49
加载中...