1. 程式人生 > >hihocoder1426—What a Ridiculous Election(bfs預處理)

hihocoder1426—What a Ridiculous Election(bfs預處理)

題目大意:

1.交換相鄰的數字 2.每個位置+1(最多操作3次) 3.每個位置乘以2(最多操作2次) 然後開始是12345,給了五位數n,然後問12345轉化成n最小操作幾步。如果不能輸出-1

 解: 用bfs,模擬出所有的12345變換情況,開個三維陣列 m[x][y][z] ,表示12345變換成x,②用了y次,③用了z次時的最少步數;

程式碼:

#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e5+10;
const int inf = 0x3f3f3f3f;

char s[10];
bool flag,vis[10];
int res[maxn][5][5];

struct node{
    int a[10],sec,thr,step;
    bool operator < (const node &a)const{
        return step > a.step;
    }
};

node target;

int check(node now){
    int num = 0;
    for(int i = 1;i <= 5;i++)
        if(now.a[i] != target.a[i]) return 0;
    return 1;
}

int turn(node now){
    int sum = 0;
    for(int i = 1;i <= 5;i++){
        sum += now.a[i];
        sum *= 10;
    }
    sum /= 10;
    return sum;
}

void bfs(node now){
    priority_queue<node>q;
    q.push(now);
    int tmp = turn(now);
    res[tmp][now.sec][now.thr] = 0;

    node u,next;
    bool flag;
    while(!q.empty()){
        u = q.top();
        q.pop();
        for(int i = 2;i <= 5;i++){
            next = u;
            next.step++;
            swap(next.a[i],next.a[i-1]);
            int p = turn(next);
            if(next.step >= res[p][next.sec][next.thr]) continue;
            q.push(next);
            res[p][next.sec][next.thr] = next.step;
        }
        if(u.sec > 0){
            for(int i = 1;i <= 5;i++){
                next = u;
                next.sec--;
                next.step++;
                next.a[i] = (next.a[i]+1)%10;
                int p = turn(next);
                if(next.step >= res[p][next.sec][next.thr]) continue;
                q.push(next);
                res[p][next.sec][next.thr] = next.step;
            }
        }
        if(u.thr > 0){
            for(int i = 1;i <= 5;i++){
                next = u;
                next.thr--;
                next.step++;
                next.a[i] = (next.a[i]*2)%10;
                int p = turn(next);
                if(next.step >= res[p][next.sec][next.thr]) continue;
                q.push(next);
                res[p][next.sec][next.thr] = next.step;
            }
        }
    }
}

int main(){
    node now;
    now.sec = 3,now.thr = 2,now.step = 0;
    for(int i = 1;i <= 5;i++) now.a[i] = i;
    memset(res,inf,sizeof(res));
    bfs(now);
    while(~scanf("%s",s)){
        for(int i = 1;i <= 5;i++) target.a[i] = s[i-1]-'0';
        int p = turn(target);
        int ans = inf;
        for(int i = 0;i <= 3;i++)
            for(int j = 0;j <= 2;j++)
                ans = min(ans,res[p][i][j]);
        if(ans == inf) puts("-1");
        else printf("%d\n",ans);
    }
    return 0;
}