Exercise(18):排列(有限制条件)

/* 陈潼升 【排列】 题目描述 Description 给出数字n以及x和y,请输出数字1~n的所有排列,但要求排列中x必须在y的左边方向,其它的数位置随意。 输入描述 Input Description 读入整数n、x和y ( 1<=n<=10,x∈[1,n],y∈[1,n] ) 输出描述 Output Description 每行n个用空格隔开的数,表示一个符合条件的排列。并且所有排列按字典序输出。 样例输入 Sample Input 3 1 2 样例输出 Sample Output 1 2 3 1 3 2 3 1 2 问题分析: 思路与Exercise(16)一样,不过多了一个条件:x必须在y的左边 可以在放数的时候记录当前数放在哪个盒子 输出时直接判断数的位置即可 */
#include <iostream>
using std::cin;
using std::cout;
using std::ends;
using std::endl;

int arr[11] = {0};          
int book[11] = {0};         // 用于储存各数的盒子位置 
bool mark[10];          
int n,x,y;

void DFS(int step)
{
    int i;
    if(step == n+1)
    {

        if(book[x]<book[y])             // 判断数x的位置是否在数y的左边,是则输出 
        {
            for(i=1;i<=n;i++)
                cout<<arr[i]<<ends;
            cout<<endl;
        }
        return;
    }

    for(i=1;i<=n;i++)
    {
        if(!mark[i])
        {
            arr[step] = i;
            mark[i] = true;
            book[i] = step;             // 存储数i的盒子位置 
            DFS(step+1);
            mark[i] = false; 
            book[i] = 0;                // 重置数i的盒子位置 
        }
    }
    return;
}

int main()
{
    cin>>n>>x>>y;
    if(n<1 || n>10) return -1;
    if(x<1 || x>n)  return -1;
    if(y<1 || y>n)  return -1;

    DFS(1);

    return 0;
}

你可能感兴趣的:(蓝桥)