首页 > 编程语言 > 详细

算法问题实战策略 SORTGAME

时间:2019-11-10 00:42:20      阅读:109      评论:0      收藏:0      [点我收藏+]

地址 https://algospot.com/judge/problem/read/SORTGAME

技术分享图片

 

 技术分享图片

 

 解答 

常规BFS是会超时的  按照书上的提示 应该是打表(居然还有提倡打表的题目)

tle 代码

技术分享图片
 1 #include <iostream>
 2 #include <vector>
 3 #include <algorithm>
 4 #include <queue>
 5 #include <map>
 6 
 7 using namespace std;
 8 
 9 int n, m;
10 
11 
12 int bfs(const vector<int>& v)
13 {
14     vector<int> sorted = v;
15     sort(sorted.begin(), sorted.end());
16     queue<vector<int>> q;
17     map<vector<int>, int> distance;
18     distance[v] = 0;
19     q.push(v);
20     while (!q.empty()) {
21         vector<int> here = q.front();
22         q.pop();
23 
24         if (here == sorted) return distance[here];
25         int cost = distance[here];
26         //翻转可能的子区间
27         for (int i = 0; i < v.size(); i++) {
28             for (int j = i + 2; j <= v.size(); ++j) {
29                 reverse(here.begin() + i, here.begin() + j);
30                 if (distance.count(here) == 0) {
31                     distance[here] = cost + 1;
32                     q.push(here);
33                 }
34                 reverse(here.begin() + i, here.begin() + j);
35             }
36         }
37     }
38 
39     return -1;
40 }
41 
42 
43 int main()
44 {
45     cin >> n;
46 
47     while (n--) {
48         cin >> m;
49         vector<int> v;
50         for (int i = 0; i < m; i++) {
51             int t;
52             cin >> t;
53             v.push_back(t);
54         }
55 
56         cout << bfs(v) << endl;
57     }
58 
59 
60     return 0;
61 }
View Code

 

算法问题实战策略 SORTGAME

原文:https://www.cnblogs.com/itdef/p/11828567.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!