#include <iostream>
#include <istream>
#include <sstream>
#include <vector>
#include <stack>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <cstring>
#include <unordered_map>
#include <unordered_set>
#include <algorithm>
#include <numeric>
#include <chrono>
#include <ctime>
#include <cmath>
#include <cctype>
#include <string>
#include <cstdio>
#include <iomanip>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <functional>
#include <iterator>
using namespace std;
const int maxn = 10;
int data[maxn],n;
bool IsOver() {
for (int i = 1; i < n; i++)
if (data[i - 1] > data[i]) return false;
return true;
}
int h()
{
int cnt = 0;
for (int i = 0; i < n - 1; i++)
if (data[i] + 1 != data[i + 1]) cnt++;
if (data[n - 1] != n) cnt++;
return cnt;
}
bool dfs(int d)
{
if (h() > d * 3) return false;
if (IsOver()) return true;
//备份
int back[maxn],back2[maxn];
memmove(back, data, sizeof(data));
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
//剪切一段 i - j
int cnt = 0;
//保存剪切的内容
for (int k = 0; k < n; k++) {
if (k < i || k > j) back2[cnt++] = data[k];
}
//粘贴
for (int ii = 0; ii <= cnt; ii++) {
int cnt2 = 0;
//插入之前的
for (int jj = 0; jj < ii; jj++) data[cnt2++] = back2[jj];
//插入的
for(int jj = i;jj<=j;jj++) data[cnt2++] = back[jj];
//插入之后的
for(int jj = ii;jj<cnt;jj++) data[cnt2++] = back2[jj];
if (dfs(d - 1)) return true;
memmove(data, back, sizeof(data));
}
}
}
return false;
}
int GetResult() {
if (IsOver()) return 0;
for (int i = 1; i < maxn; i++) {
if (dfs(i)) return i;
}
return maxn;
}
int main()
{
int id = 0;
while (cin >> n && n) {
for (int i = 0; i < n; i++) cin >> data[i];
cout << "Case " << ++id << ": " << GetResult() << endl;
}
return 0;
}
例题7-10(uva-11212)
最新推荐文章于 2021-05-25 19:37:40 发布
该篇博客探讨了一种利用深度优先搜索(DFS)解决序列排序问题的方法。通过递归地剪切和粘贴序列段,判断是否达到升序状态,博主展示了如何在不超过给定操作次数限制的情况下找到最小的操作步数。代码实现中涉及了多种数据结构和算法,如栈、队列、映射等,并在主函数中读取输入并输出结果。
458

被折叠的 条评论
为什么被折叠?



