hihocoder1426—What a Ridiculous Election(bfs预处理)

版权声明:本文为博主原创文章,转载请说明出处。 https://blog.csdn.net/xianpingping/article/details/82940242

题目大意:

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;
}

猜你喜欢

转载自blog.csdn.net/xianpingping/article/details/82940242