UVa #11925 Generating Permutations (习题8-7)
来源:互联网 发布:亚马逊ara数据 编辑:程序博客网 时间:2024/05/04 13:05
感觉把题目要求的过程反过来做会比较简单:把一个乱序的序列排成升序
做着做着觉得其实就是冒泡排序的改版嘛。如果最前面两个数不满足a<b,且 a != n-1 && b != 1(即:不是开头和结尾的交汇点),则反转这两个数,然后挪动一位,再反复
复杂度大概是O(n^2),还没有超过2*n^2的要求。这几天上mit的算法导论公开课,Eric说每次只能调换相邻两位元素的排序算法,复杂度下限是n^2。
Run Time: 0.192s
#define UVa "8-7.11925.cpp" //Generating Permutationschar fileIn[30] = UVa, fileOut[30] = UVa;#include<cstring>#include<cstdio>#include<vector>using namespace std;//Global Variables. Reset upon Each Case!const int maxn = 500;int n;int next[maxn], prev[maxn], a[maxn];vector<int> ans;/////int op(int code) { ans.push_back(code); if(code == 1) { //swap first two. int a = next[0], b = next[a]; int tmp = next[b]; next[a] = tmp; prev[tmp] = a; prev[a] = b; next[b] = a; prev[b] = 0; next[0] = b; } else if(code == 2) { //move to front. int a = next[0], b = prev[n+1]; int tmp = next[a]; next[prev[b]] = n+1; prev[n+1] = prev[b]; next[b] = a; prev[b] = 0; prev[a] = b; next[0] = b; }}void init() { ans.clear(); memset(next, 0, sizeof(next)); memset(prev, 0, sizeof(prev)); for(int i = 1; i <= n; i ++) { scanf("%d", &a[i]); next[i] = i+1; prev[i] = i-1; } next[n] = 0; prev[0] = 0; prev[n+1] = n; next[0] = 1;}int invalid() { int u = next[0], cnt = 0; while(next[u] && next[u] != n + 1) { if(a[u] && a[next[u]] && a[u] > a[next[u]]) return 1; u = next[u]; cnt ++; } return 0;}int main() { while(scanf("%d", &n) && n) { init(); while(invalid()) { int a1 = a[next[0]], a2 = a[next[next[0]]]; if(a1 > a2 && (a1 != n || a2 != 1)) op(1); op(2); } for(int i = ans.size() - 1; i >= 0; i --) printf("%d", ans[i]); printf("\n"); } return 0;}
0 0
- UVa #11925 Generating Permutations (习题8-7)
- 习题8-7 UVA - 11925 Generating Permutations 生成排列(构造)
- UVa:11925 Generating Permutations
- UVa 11925 - Generating Permutations
- UVa 11925 Generating Permutations
- UVa - 11925 - Generating Permutations
- UVA 11925 Generating Permutations
- UVA 11925 - Generating Permutations
- UVA - 11925 Generating Permutations 推理
- UVA 11925(p254)----Generating Permutations
- UVa 11925 - Generating Permutations(构造法)
- UVa 11925:Generating Permutations(构造)
- uva 11925——Generating Permutations
- UVA 11925 Generating Permutations 逆向思维
- Generating Permutations UVA
- 11925 - Generating Permutations
- 生成排列 Generating Permutations
- 紫书搜索 习题7-8 UVA
- [Android] ListView中getView的原理+如何在ListView中放置不同的布局
- Java基础
- codeforces 366C Dima and Salad (01背包)
- Compile, Install, Run Linux Apps on Android
- jquery js获取html选中的内容
- UVa #11925 Generating Permutations (习题8-7)
- User Defined Runtime Attributes
- Android拍照获取原图片出现问题
- 【LeetCode】Valid Sudoku
- HDOJ 题目4858 项目管理(vector水)
- 单例模式与线程
- 处理python爬虫的timeout报错
- sql server2008 用户登录失败 错误18457 解决
- ffmpeg多线程转码