昨晚十一點第一次完成這道題目……
但是呢因爲上次的算法用了一點“小聰明”,所以一直覺得不妥。
於是今天下午絞盡腦汁地想怎麼對廣搜進行優化
無意間看了一下老師的教案,發現這道題的分類竟然在“雙向廣搜”裏面!!
What??還有雙向廣搜這種東西??以前竟然從來沒有聽說過
於是乎上網查了一下雙向廣搜是什麼東西,用新的方法處理了這道題目。
這次穩妥了。
又Get了一個新技能,哈哈哈
下附代碼:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <queue>
using namespace std;
const int que_len = 10000;
char Str[2][6+2][20+2];
char tmp, Left[255], Right[255];
char *p;
int cnt = 1;
struct NODE{
char str[255];
int step;
}node, New;
NODE que[2][que_len];
int front[2], back[2];
void check_Meet(NODE Get, int n){
for(int i = 0; i<back[n]; ++i) if(strcmp(que[n][i].str, Get.str)==0){
printf("%d\n", Get.step+que[n][i].step);
exit(0);
}
}
bool check_Re(char str[], int n){
for(int i = 0; i<back[n]; ++i) if(strcmp(str, que[n][i].str)==0) return true;
return false;
}
void expand(int n){
node = que[n][front[n]++];
if(node.step>10){
printf("NO ANSWER!\n");
exit(0);
}
for(int i = 1; i<=cnt; ++i){
p = node.str;
while(strstr(p, Str[n][i])!=NULL){
p = strstr(p, Str[n][i]);
tmp = *p;
*p = 0;
strcpy(Left, node.str);
*p = tmp;
p += strlen(Str[n][i]);
strcpy(Right, p);
strcpy(New.str, "");
strcat(New.str, Left);
strcat(New.str, Str[n^1][i]);
strcat(New.str, Right);
New.step = node.step+1;
if(check_Re(New.str, n)) continue;
check_Meet(New, n^1);
que[n][back[n]++] = New;
}
}
}
void doubleBFS(){
node.step = 0;
strcpy(node.str, Str[0][0]); que[0][back[0]++] = node;
strcpy(node.str, Str[1][0]); que[1][back[1]++] = node;
while(front[0] < back[0] && front[1] < back[1]){
if(back[0]<back[1]) expand(0);
else expand(1);
}
}
int main() {
freopen("noip02b.in", "r", stdin); freopen("noip02b.out", "w", stdout);
cin >> Str[0][0] >> Str[1][0];
while(cin >> Str[0][cnt]) cin >> Str[1][cnt++];
--cnt;
doubleBFS();
printf("NO ANSWER!\n");
fclose(stdin); fclose(stdout); return 0;
}
評測信息來自濰坊七中信息技術論壇在線評測(因爲CodeVS突然登不上去)