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;
    }
    
  • 相关阅读:
    第 9 章
    第 8 章
    第 7 章
    第 6 章
    第 5 章
    第 4 章
    跳舞链解数独
    minic 类型声明与变量定义句型处理
    minic 动作句型处理
    minic 符号表
  • 原文地址:https://www.cnblogs.com/CSLaker/p/7281225.html
Copyright © 2011-2022 走看看