【STL】prev

    xiaoxiao2021-03-25  69

    #include <iostream> #include <algorithm> using namespace std; /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int main(int argc, char *argv[]) { double a[] = {3, 2, 1}; while(prev_permutation(a,a+3)) { for(int i=0;i<3;i++) cout<<a[i]<<" "; } return 0; }

    prev_pertutation使用的时候输入的数据需要都为降序;

    输出:3 1 2 

              2 3 1 

                2 1 3 

       1 3 2 

       1 2 3

    同理,prev_pertutatiom则相反

    使用这两个函数的时候,应包含头文件#include<algorithm>

    prev_pertutatiom(a,a+9)

    a是地址,9是需要排列的长度

    例:

    方格填数 如下的10个格子 填入0~9的数字。要求:连续的两个数字不能相邻。 (左右、上下、对角都算相邻) 一共有多少种可能的填数方案? 请填写表示方案数目的整数。 注意:你提交的应该是一个整数,不要填写任何多余的内容或说明性文字。

    这题可以采用暴力或者dfs,但是用next_pertutation会使代码精简很多

    #include<cstdio> #include<cstring> #include<algorithm> using namespace std; /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int a[10]={0,1,2,3,4,5,6,7,8,9}; int c; bool judge() { if(abs(a[0]-a[1])!=1&&abs(a[0]-a[4])!=1&&abs(a[0]-a[5])!=1&&abs(a[0]-a[3])!=1) if(abs(a[1]-a[2])!=1&&abs(a[1]-a[4])!=1&&abs(a[1]-a[5])!=1&&abs(a[1]-a[6])!=1) if(abs(a[2]-a[5])!=1&&abs(a[2]-a[6])!=1) if(abs(a[3]-a[4])!=1&&abs(a[3]-a[8])!=1&&abs(a[3]-a[7])!=1) if(abs(a[4]-a[5])!=1&&abs(a[4]-a[7])!=1&&abs(a[4]-a[8])!=1&&abs(a[4]-a[9])!=1) if(abs(a[5]-a[6])!=1&&abs(a[5]-a[8])!=1&&abs(a[5]-a[9])!=1) if(abs(a[6]-a[9])!=1)if(abs(a[7]-a[8])!=1)if(abs(a[8]-a[9])!=1)return true; return false; } int main() { c=0; do{ if(judge()) c++; }while(next_permutation(a,a+10)); cout<<c; return 0; }

    转载请注明原文地址: https://ju.6miu.com/read-35581.html

    最新回复(0)