LQB2017A02跳蚱蜢

 

为什么第二题就这么难呜呜呜,这不是为难我吗!!!

可以明确的是,又是一个bfs

最少路径,找满足条件的那个层数

 1 #include<iostream>
 2 #include<stdio.h>
 3 #include<stdlib.h>
 4 #include<time.h>
 5 #include <strings.h>
 6 #include <queue>
 7 #include <set>
 8 #include <cstring>
 9 
10 using namespace std;
11 char *start="0123456789";
12 char *target="0987654321";
13 
14 
15 struct StateAndLevel{
16     char *state;
17     int level;
18     int pos0;//记录0的位置
19     StateAndLevel(char *_state,int _level,int _pos0):state(_state),level(_level),pos0(_pos0){};//构造函数
20 };
21 
22 void swap(char *s,int a,int b) {
23     char t=s[a];
24     s[a]=s[b];
25     s[b]=t;
26 }
27 struct cmp{
28     bool operator ()(char *a,char *b){
29         return strcmp(a,b)<0;
30 
31     }
32 };
33 queue<StateAndLevel> q;
34 
35 set<char *,cmp> allState;//set需要重载一下()运算符:set是用来去重的,但是你得定义啥是重复啊
36 
37 void addN(char *state,int pos,int newpos,int le){
38 
39     //添加其他队列成员
40     char *new_state1 = (char *) malloc(9 * sizeof(char));
41     strcpy(new_state1, state);//把原字符串拷贝过来,然后进行改变
42     //首先寻找一下合适的位置
43 
44     //移动字符以形成新的字符串
45     swap(new_state1, pos, newpos);
46     //将改变后的字符插入到set和queue里,注意需要判断是否重复
47     if (allState.find(new_state1) == allState.end()) {
48         allState.insert(new_state1);
49         q.push(StateAndLevel(new_state1, le + 1, newpos));//注意你现在操作的是sal的成员
50     }
51 }
52 
53 int main() {
54     q.push(StateAndLevel(start, 0, 0));//先把初始的放进去
55     while (!q.empty())//套路!!!
56     {
57         StateAndLevel sal = q.front();
58 
59         char *state = sal.state;
60         int le = sal.level;
61         cout<<le<<" "<<endl;
62         if (strcmp(state, target) == 0) {
63             cout << le;
64             return 0;
65         }
66         int pos = sal.pos0;//取出所有的当前值,添加到set中去
67         allState.insert(state);
68 
69         int newpos = (pos + 1 + 9) % 9;
70         addN(state, pos, newpos, le);
71 
72         int newpos2 = (pos - 1 + 9) % 9;
73         addN(state, pos, newpos2, le);
74 
75         int newpos3 = (pos - 2 + 9) % 9;
76         addN(state, pos, newpos3, le);
77 
78         int newpos4 = (pos + 2 + 9) % 9;
79         addN(state, pos, newpos4, le);
80         q.pop();
81 
82     }
83 
84 }

那个add函数,

就是生成一个新的位置,

更改出那个新的字符

然后level+1

其实用bfs搞最小挺常见的emmmmmm

原文地址:https://www.cnblogs.com/zhmlzhml/p/13289369.html