zoukankan      html  css  js  c++  java
  • 【搜索】POJ-3187 枚举全排列

    一、题目

    Description

    FJ and his cows enjoy playing a mental game. They write down the numbers from 1 to N (1 <= N <= 10) in a certain order and then sum adjacent numbers to produce a new list with one fewer number. They repeat this until only a single number is left. For example, one instance of the game (when N=4) might go like this: 
    ​ 3 1 2 4
    ​ 4 3 6
    ​ 7 9
    ​ 16

    Behind FJ's back, the cows have started playing a more difficult game, in which they try to determine the starting sequence from only the final total and the number N. Unfortunately, the game is a bit above FJ's mental arithmetic capabilities. 
    Write a program to help FJ play the game and keep up with the cows.

    Input

    Line 1: Two space-separated integers: N and the final sum.

    Output

    Line 1: An ordering of the integers 1..N that leads to the given sum. If there are multiple solutions, choose the one that is lexicographically least, i.e., that puts smaller numbers first.

    Sample Input

    4 16
    

    Sample Output

    3 1 2 4
    

    Hint

    Explanation of the sample: 
    There are other possible sequences, such as 3 2 1 4, but 3 1 2 4 is the lexicographically smallest.

    二、思路&心得

    • 利用next_permutation()函数生成全排列,暴力搜索

    三、代码

    #include<cstdio>
    #include<algorithm>
    using namespace std;
    
    int N, sum;
    
    int a[11], b[11];
    
    void solve() {
    	for (int i = 0; i < N; i ++) {
    		a[i] = i + 1;
    	}
    	do {
    		for (int i = 0; i < N; i ++) {
    			b[i] = a[i];
    		}
    		for (int i = N - 1; i > 0; i --) {
    			for (int j = 0; j < i; j ++) {
    				b[j] += b[j + 1];
    			}
    		}
    		if (b[0] == sum) {
    			for (int i = 0; i < N; i ++) {
    				printf("%d ", a[i]);
    			}
    			printf("
    ");
    			break;
    		}
    	} while (next_permutation(a, a + N));
    }
    
    int main() {
    	while (~scanf("%d %d", &N, &sum)) {
    		solve();
    	}
    	return 0;
    }
    
  • 相关阅读:
    springboot2 整合雪花算法,并兼容分布式部署
    docker 在 linux 搭建私有仓库
    jdbc 几种关系型数据库的连接 和 driver_class,以及简单的使用
    springboot2 整合发送邮件的功能
    oracle 唯一新约束 和 逻辑删除的 冲突处理办法
    oracle 一些常见操作方法
    spring-cloud-stream 整合 rabbitmq
    springboot2 整合 rabbitmq
    docker 安装 rabbitmq 消息队列
    网络统计学目录
  • 原文地址:https://www.cnblogs.com/CSLaker/p/7281225.html
Copyright © 2011-2022 走看看