UVA 11925 Generating Permutations

来源:互联网 发布:青岛seo排名优化公司 编辑:程序博客网 时间:2024/05/18 12:44

构造法吧,类似冒泡排序,当队首是n的时候特判不换前两个位置了。

#include <iostream>#include <algorithm>#include <cstdio>#include <cstdlib>#include <cstring>#include <list>#include <vector>using namespace std;const int INF = 0x7fffffff;const int maxn = 300+5;int n, a[maxn];bool is() {    for(int i = 0; i < n; ++i)        if(a[i] != i+1) return false;    return true;}void change() {    int t = a[n-1];    for(int i = n - 1; i >= 0; --i)        a[i] = a[i-1];    a[0] = t;}int main() {    while(scanf("%d", &n) != EOF && n) {        vector<int> ans;        for(int i = 0; i < n; ++i)            scanf("%d", &a[i]);        while(!is()) {            if(a[0] != n && a[0] > a[1]) {                swap(a[0], a[1]);                ans.push_back(1);            }            if(is()) break;            change();            ans.push_back(2);        }        for(int i = ans.size() - 1; i >= 0; --i)            printf("%d", ans[i]);        printf("\n");    }    return 0;}


0 0
原创粉丝点击