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;
    }
    
  • 相关阅读:
    映射和分析
    文档操作
    向 Nginx 主进程发送 USR1 信号
    ES集群7.3.0设置快照,存储库进行索引备份和恢复等
    ES7.3.0配置邮件告警
    Elasticsearch 史上最全最常用工具清单
    Grok在线调试网址
    Linux 小知识翻译
    Linux 小知识翻译
    Linux 小知识翻译
  • 原文地址:https://www.cnblogs.com/CSLaker/p/7281225.html
Copyright © 2011-2022 走看看