Sicily 1515. 魔版C

本文解析了一道ACM编程竞赛题目,通过三种不同的字符串变换方法(A、B、C),寻找从初始状态到目标状态的最短变换路径。代码采用C++编写,并实现了BFS算法来遍历所有可能的状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

换汤不换药,还想用个N<=100来唬我……果断无视,把变换方案改一下,接着AC。

Run Time: 0.22sec

Run Memory: 4528KB

Code length: 1978Bytes

SubmitTime: 2012-01-07 19:43:21

// Problem#: 1515
// Submission#: 1180217
// The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License
// URI: http://creativecommons.org/licenses/by-nc-sa/3.0/
// All Copyright reserved by Informatic Lab of Sun Yat-sen University
#include <cstdio>
#include <string>
#include <queue>
#include <map>
using namespace std;

void changeA( const string &s, string &t );
void changeB( const string &s, string &t );
void changeC( const string &s, string &t );

int main()
{
    int M;
    string now, target;
    int i, j;

    map<string, string> m;
    target = "12345678";
    m[ target ].clear();
    queue<string> q;
    q.push( target );
    while ( !q.empty() ) {
        now = q.front();
        changeA( now, target );
        if ( m.find( target ) == m.end() ) {
            m[ target ] = m[ now ] + 'A';
            q.push( target );
        }
        changeB( now, target );
        if ( m.find( target ) == m.end() ) {
            m[ target ] = m[ now ] + 'B';
            q.push( target );
        }
        changeC( now, target );
        if ( m.find( target ) == m.end() ) {
            m[ target ] = m[ now ] + 'C';
            q.push( target );
        }
        q.pop();
    }

    while ( scanf( "%d", &M ) && M != -1 ) {
        for ( i = 0; i < 8; i++ ) {
            scanf( "%d", &j );
            target[ i ] = '0' + j;
        }
        if ( m.find( target ) == m.end() || m[ target ].size() > M )
            printf( "-1\n" );
        else
            printf( "%d %s\n", m[ target ].size(), m[ target ].c_str() );
    }
    
    return 0;

}


void changeA( const string &s, string &t ) {
    t[ 0 ] = s[ 2 ];
    t[ 1 ] = s[ 3 ];
    t[ 2 ] = s[ 0 ];
    t[ 3 ] = s[ 1 ];
    t[ 4 ] = s[ 6 ];
    t[ 5 ] = s[ 7 ];
    t[ 6 ] = s[ 4 ];
    t[ 7 ] = s[ 5 ];
}

void changeB( const string &s, string &t ) {
    t[ 0 ] = s[ 1 ];
    t[ 1 ] = s[ 2 ];
    t[ 2 ] = s[ 3 ];
    t[ 3 ] = s[ 0 ];
    t[ 4 ] = s[ 5 ];
    t[ 5 ] = s[ 6 ];
    t[ 6 ] = s[ 7 ];
    t[ 7 ] = s[ 4 ];
}

void changeC( const string &s, string &t ) {
    t[ 0 ] = s[ 0 ];
    t[ 1 ] = s[ 2 ];
    t[ 2 ] = s[ 6 ];
    t[ 3 ] = s[ 3 ];
    t[ 4 ] = s[ 4 ];
    t[ 5 ] = s[ 1 ];
    t[ 6 ] = s[ 5 ];
    t[ 7 ] = s[ 7 ];
}                                 


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值