P1032 [NOIP2002 提高组] 字串变换(洛谷)

bfs:

经典 二重for循环:
1格子(字符串)8方向(选择)

while(!q.empty())
queue遍历
priority_queue优先级

void bfs() {
    int ans = 0;
    node u, v; u.str = s, u.step = 0;
    q.push(u);
    while (!q.empty()) {
        u = q.front(); q.pop();
        if (maps.count(u.str)) continue;
        if (u.str == x) {
            ans = u.step; break;
        }
        maps[u.str] = 1;//map!判重
        for (int i = 0; i < u.str.length(); i++) {
            for (int j = 0; j < n; j++) {
                v.str = trans(u.str, i, j);
                if (v.str != " ") {
                    v.step = u.step + 1; q.push(v);
                }
            }
        }
    }
    if (ans == 0 || ans > 10) cout << "NO ANSWER!";
    else cout << ans;
}

有序
(1) pair<int, int> p**;**
p.first & p.second
q.push(make_pair(u, v))

queue<node>

无序
(2) struct node() {
int a, b;
} n[10];
n.a & n.b
q.push(n)

map<key, value> maps;
if (m.count(n.b) == 1) //判重!!!
m[n.b] = 1

pass-by-reference 引用传递
function (const string &str)
&str 形参取址实参
const 常变量(保证引用,不作值的修改)

题目

在这里插入图片描述

code

#include<iostream>
#include<string>
#include<queue>
#include<map>
using namespace std;
map<string, int> maps;
struct node {
    string str; int step;
};
queue<node> q;
string s, x, a[15], b[15];
int n = 0;

string trans(const string &str, int i, int num) {
    if (i + a[num].length() > str.length()) return " ";
    for (int j = 0; j < a[num].length(); j++)
        if (str[i + j] != a[num][j]) return " ";
    string nxt =  str.substr(0, i);
    nxt += b[num];
    nxt += str.substr(i + a[num].length());//a:original
    return nxt;
}
void bfs() {
    int ans = 0;
    node u, v; u.str = s, u.step = 0;
    q.push(u);
    while (!q.empty()) {
        u = q.front(); q.pop();
        if (maps.count(u.str)) continue;
        if (u.str == x) {
            ans = u.step; break;
        }
        maps[u.str] = 1;
        for (int i = 0; i < u.str.length(); i++) {
            for (int j = 0; j < n; j++) {
                v.str = trans(u.str, i, j);
                if (v.str != " ") {
                    v.step = u.step + 1; q.push(v);
                }
            }
        }
    }
    if (ans == 0 || ans > 10) cout << "NO ANSWER!";
    else cout << ans;
}

int main() {
    cin >> s >> x;
    while(cin >> a[n] >> b[n]) n++;
    bfs();
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值