FZU 1571 排列的字典序问题
来源:互联网 发布:sql注入 from 编辑:程序博客网 时间:2024/05/01 09:42
Description
n个元素{1,2,...,n}有n!个不同的排列。将这n!个排列按字典序排列并编号为0,1,...,n!-1。每个排列的编号为其字典序值。例如,当n=3时,6个不同排列的字典序值如下:
给定n,以及n个元素{1,2,...,n}的一个排列,计算出这个排列的字典序值,以及按字典序排列的下一个排列。
Input
输入包括多组数据。
每组数据的第一行是元素个数n(1<=n<=13),接下来1行是n个元素{1,2,...,n}的一个排列。
Output
对于每组数据,输出两行,第一行是字典序值,第2行是字典序排列的下一个排列。
Sample Input
82 6 4 5 8 1 7 3
Sample Output
82272 6 4 5 8 3 1 7
其实就是一个康托展开和逆康托展开...
STL做法(以前的 现在觉得好怪):
#include <iostream>#include <algorithm>using namespace std;typedef long long ll;int input[15];ll fact(int n){ ll res=1; for(int i=2;i<=n;i++) { res*=i; } return res;}int main(){ int a; while(cin>>a) { ll res=0; for(int i=0;i<a;i++) cin>>input[i]; for(int i=0;i<a;i++) { int cou=input[i]-1; for(int j=0;j<i;j++) if(input[j]<input[i]) cou--; res+=cou*fact(a-i-1); } cout<<res<<endl; next_permutation(input,input+a); for(int i=0;i<a;i++) { if(i) cout<<' '; cout<<input[i]; } cout<<endl; } return 0;}
逆康托展开:
#include <cstdio>#include <cstring>#include <cmath>#include <iostream>#include <algorithm>#include <queue>#include <map>#include <string>#include <stack>#include <bitset>#include <vector>using namespace std;int a[20], fact[20];int main() { #ifdef LOCAL freopen("in.txt", "r", stdin); //freopen("out.txt", "w", stdout); #endif int n; while(~scanf("%d", &n)) { fact[0] = 1; vector<int> num; num.clear(); for(int i = 0; i < n; i++) { scanf("%d", &a[i]); num.push_back(i + 1); if(i) fact[i] = i * fact[i - 1]; } int X = 0; for(int i = 0; i < n; i++) { int ran = 0; for(int j = i; j < n; j++) { if(a[j] < a[i]) ran++; } X += fact[n - 1 - i] * ran; } printf("%d\n", X); X++; for(int i = 0; i < n; i++) { int quot = X / fact[n - 1 - i], rem = X % fact[n - 1 - i]; a[i] = num[quot]; num.erase(num.begin() + quot); X = rem; } for(int i = 0; i < n; i++) { printf("%d%c", a[i], i == n - 1 ? '\n' : ' '); } } return 0;}
0 0
- FZU 1571 排列的字典序问题
- foj 1571 排列的字典序问题
- foj 1571 排列的字典序问题
- 排列的字典序问题
- 排列的字典序问题
- 排列的字典序问题
- 排列的字典序问题
- 排列的字典序问题
- 排列的字典序问题
- 排列的字典序问题
- 排列的字典序问题
- 排列的字典序问题
- 排列的字典序问题
- 排列的字典序问题
- 排列的字典序问题
- 排列的字典序问题
- 排列的字典序问题
- 排列的字典序问题
- 初窥 quick-cocos2d-x
- Exercise 16: 读写文件
- jQuery基础教程学习笔记·第二章
- 文件批量下载
- UML核心模型
- FZU 1571 排列的字典序问题
- cocos2d-x 2.2 创建项目
- tag 标签开发 note
- 用Android平板与RaspberryPi配置便携物理渗透设备(Pwn Pad & PwnPi)
- smack+openfire插件实现广播。向所有在线用户发送消息。
- 20140313
- struts2 注解的使用
- 两个chrome 同步软件
- 条件编译指令