搜索—uva 12160
Unlock the Lock
题目描述

输入格式

输出格式

样例 #1
样例输入 #1
0000 9999 1
1000
0000 9999 1
0001
5234 1212 3
1023 0101 0001
0 0 0
样例输出 #1
Case 1: Permanently Locked
Case 2: 9999
Case 3: 48
分析
题目大意就是给定初始状态,通过每次加固定大小的值,变成结束状态,使得操作次数最少,简单的搜索题,用bfs加set判重,但要注意题目中的小细节。
代码实现
#include <iostream>
#include <set>
#include <queue>
#include <cstring>
using namespace std;
int rr[10];
int L, U, R, ans = 0;
bool flag;
set<int> mp;
struct node
{
int val = 0;
int ans = 0;
};
int bfs() {
queue<node> q;
node fir;
fir.val = L;
q.push(fir);
while (!q.empty()) {
node now = q.front();
q.pop();
if (now.val == U) {
flag = true;
return now.ans;
}
for (int i = 0; i < R; i++) {
node next;
next.val = (now.val + rr[i]) % 10000;
if (mp.find(next.val) == mp.end()) {
next.ans = now.ans + 1;//不要直接ans++这样会使得ans一直增加。也就是说在队列里面,如果队头元素等于U那此时对应的ans应该就是队头元素对应的U,而此时ans确实对应的队尾元素的ans(因为bfs是一层一层搜索的)
mp.insert(next.val);
q.push(next);
}
}
}
return -1;
}
int main() {
int caseNum = 0;
while (cin >> L >> U >> R) {
if (L == 0 && U == 0 && R == 0)
break;
memset(rr, 0, sizeof(rr));
ans = 0;
mp.clear();
for (int i = 0; i < R; i++)
cin >> rr[i];
flag = false;
ans = bfs();
caseNum++;
if (flag)
cout << "Case " << caseNum << ": " << ans << endl;
else
cout << "Case " << caseNum << ": Permanently Locked" << endl;
}
return 0;
}

浙公网安备 33010602011771号