HDU-1027 Ignatius and the Princess II
HDU-1027 Ignatius and the Princess II
题意
给出 n,m,求出从 1 - n 的第 m 小的序列。
thinking
利用 STL 里的求下一个排列组合的函数 next_permutation()。
next_permutation()求出一个序列字典序的下一个,排序范围是 [ first, last ).
code
#include <iostream>
#include <algorithm>
using namespace std;
int a[10009];
int main(){
int n,m;
while (cin >> n >> m){
for (int i = 1; i <= n; ++i) {
a[i] = i;
}
int count=1;
while (count<m){
next_permutation(a+1,a+1+n);
count++;
}
for (int j = 1; j <= n; ++j) {
cout << a[j];
if (j!=n) cout << ' ';
}
cout << endl;
}
}
HDU-1716 排列2
题意
给出四个数
按照从小到大排序
千位数一样的为一行
样例之间空一行
最后一个样例之后不空
think
一开始没有很好的理解 next_permutation()以至于出现重复的,处理了一番,白饶了一圈。
next_permutation()如果没有下一个排列将会返回 false,所以可以直接判断有无排列过,就不会存在重复的了。
用 flag 帮助输出空格的情况。
输入数字后在判断是否为最后一个数,来判断是否要输出空格。
code
#include <iostream>
#include <algorithm>
using namespace std;
int a[10009];
int main(){
cin >> a[0] >> a[1] >> a[2] >> a[3];
while ((a[0]||a[1]||a[2]||a[3])){
int th = a[0];
int flag=0;
do{
if (a[0]==th&&a[0]){
if (flag) cout << ' ';
printf("%d%d%d%d",a[0],a[1],a[2],a[3]);
flag=1;
} else if(a[0]){
if (th){
th = a[0];
printf("\n%d%d%d%d",a[0],a[1],a[2],a[3]);
} else{
th = a[0];
printf("%d%d%d%d",a[0],a[1],a[2],a[3]);
flag=1;
}
}
}while(next_permutation(a, a + 4));
cout <<'\n';
cin >> a[0] >> a[1] >> a[2] >> a[3];
if ((a[0]||a[1]||a[2]||a[3])) cout<<"\n";
}
}