nyoj 19 擅長排列的小明

擅長排列的小明

時間限制:1000 ms  |  內存限制:65535 KB
難度:4
描述
小明十分聰明,而且十分擅長排列計算。比如給小明一個數字5,他能立刻給出1-5按字典序的全排列,如果你想爲難他,在這5個數字中選出幾個數字讓他繼續全排列,那麼你就錯了,他同樣的很擅長。現在需要你寫一個程序來驗證擅長排列的小明到底對不對。
輸入
第一行輸入整數N(1<N<10)表示多少組測試數據,
每組測試數據第一行兩個整數 n m (1<n<9,0<m<=n)
輸出
在1-n中選取m個字符進行全排列,按字典序全部輸出,每種排列佔一行,每組數據間不需分界。如樣例
樣例輸入
2
3 1
4 2
樣例輸出
1
2
3
12
13
14
21
23
24
31
32
34
41
42
43

我們可以先求字符串s的全排列, 然後取s全排列的前y位組成的不同字符串(要檢查所取子串是否與前面輸出的子串相同,不同才輸出)
例: x = 3, y = 1;
s = “123”
s的全排列爲
123
132
213
231
312
321
而我們要取的爲
1
2
3
#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
int T, x, y;
int main() {
    cin >> T;
    while(T--) {
        string s, t, ts;
        //字符串s放在while裏面定義,如果在外面定義,應該每次循環時清空s
        cin >> x >> y;
        for(int i = 1; i <= x; i++) {
            s += '0' + i;
        }
        t = s.substr(0, y);
        //取s從第0位開始,由y位字符組成的子串
        cout << t << endl;
        while(next_permutation(s.begin(), s.end())) {
            ts = s.substr(0, y);
            if(ts != t) {
                cout << ts << endl;
                t = ts;
            }
        }
    }
    return 0;
}



法二:
#include <stdio.h>  
#include <string.h>  
#include <stdlib.h>  
#include <algorithm>  
using namespace std;  
int n,m,used[10];  
char ans[11];  
void dfs(int x,int num)  {  
    if(num==m-1) {  
        ans[m]='\0';  
        printf("%s\n",ans);  
        return;  
    }  
    int i;  
    for(i=1;i<=n;i++) {  
        if(!used[i]) {  
            used[i]=1;  
            ans[num+1]=i+'0';  
            dfs(i,num+1);  
            used[i]=0;  
        }  
    }  
}  
int main() {  
    int i,t;  
    scanf("%d",&t);  
    while(t--) {  
        scanf("%d%d",&n,&m);  
        for(i=1;i<=n;i++) {  
            memset(used,0,sizeof(used));  
            used[i]=1;  
            ans[0]=i+'0';  
            dfs(i,0);  
        }  
    }  
    return 0;  
}          





附:求1.......x的升序全排列代碼(1<= x && x <= 9)
#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
string s;
int T, x, y;
int main() {
    cin >> T;
    while(T--) {
        cin >> x >> y;
        for(int i = 1; i <= x; i++) {
            s += '0' + i;
        }
        cout << s << endl;
        while(next_permutation(s.begin(), s.end())) {
            cout << s << endl;
        }
    }
}

升序全排列 next_permutation()
降續全排列 prev_permutation()

說明:next_permutation,重新排列範圍內的元素[第一,最後一個)返回按照字典序排列的下一個值較大的組合。

返回值:如果有一個更高的排列,它重新排列元素,並返回true;如果這是不可能的(因爲它已經在最大可能的排列),它按升序排列重新元素,並返回false。





發佈了40 篇原創文章 · 獲贊 6 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章