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;
    }
    
  • 相关阅读:
    li排序
    appendChild的用法
    单选框和下拉框的jquery操作
    Dom操作高级应用
    DOM操作应用
    自己写的sql排序
    odoo10学习笔记七:国际化、报表
    odoo10学习笔记六:工作流、安全机制、向导
    odoo10学习笔记五:高级视图
    odoo10学习笔记四:onchange、唯一性约束
  • 原文地址:https://www.cnblogs.com/CSLaker/p/7281225.html
Copyright © 2011-2022 走看看