p1032 子串變換 解題記錄

2021-07-30 07:10:21 字數 1479 閱讀 5996

原題點 這裡

這是一道經典的搜尋問題,但是資料比較弱,直接用寬度優先搜尋就能通過。

簡單地說,思路就是:

把原字串入隊,並設該元素之前的變換次數為 0 。

取出隊首元素,如果隊列為空,則沒有答案,結束程式。

如果該元素等於目標字串,輸出它的變換次數,結束程式。

檢查該元素之前是否出現過,如果是則不必重複搜尋,返回第 2 步。

檢查該元素之前的變換次數是否達到 10 。是則不能再變換返回第 2 步。

列舉它所有的變換結果,令其變換次數增加 1,然後入隊。

回到第 2 步。

用偽**描述一下的話,就是:

read(origin: 原字串, target: 目標字串, rule: 變換規則);

var queue: 空佇列, visited: 空集合;

queue.push(); //

while(queue 不空) = queue.front();

queue.pop_front();

if(str==target)

if(str in visited or cnt>=10) continue;

visited.insert(str);

for(t = str 按照 rule 變換的每乙個結果));

}} print("no answer!"); exit(0);

c++ **如下:

#include 

#include

#include

#include

#include

#include

using

namespace

std;

struct unit;

typedef

vector

string,string> >::iterator iter;

string origin, target;

vector

string,string> > rule;

set visited;

queue

q;void bfs());

while(!q.empty())

if(cnt>=10||visited.find(s)!=visited.end()) continue;

visited.insert(s);

for(iter beg= rule.begin(), end= rule.end(); beg!=end; ++beg));}}

}cout

<<"no answer!\n";

exit(0);

}int main()

bfs();

return

0;}

實際上,該題還可以用 dfs+剪枝,或者雙向 bfs 解決,可達到更高的效能。這裡就不貼**了。

P1032 字串變換

思路 採用bfs 我們遍歷字串a的每個字元,判斷當前字串i位置之後可不可以替換,如果可以替換,我們就把替換後的字串 a 放入佇列。如果出現的我們想要的字串,根據bfs的性質,那麼就直接記錄此時的步數。1 include 2 include 3 include 4 include 5 include ...

P1032 字串變換

迭代加深難題 右手進入傳送門 大意是這樣的 給定兩個字串a,b以及至多六個變換規則 規則指a1 b1,a2 b2,在a中的子串 a1可以變換為b1,a2可以變換為 b2 求最少變換步數,若在10步 包含10步 以內能將a變換為b,則輸出最少的變換步數 否則輸出 no answer 看到題目要求的10...

P1032 字串變換

已知有兩個字串 a,b 及一組字串變換的規則 至多6個規則 a1 b1 a2 b2 規則的含義為 在 a 中的子串 a1 可以變換為 b1 a2 可以變換為 b2 例如 a abcd b xyz 變換規則為 abc xu ud y y yz 則此時,a 可以經過一系列的變換變為 b,其變換的過程為 ...