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;
    }
    
  • 相关阅读:
    Jmeter性能测试--自己看到的博客收集
    python日志logging
    java学习day12--API-File文件流
    java学习day12--API-IO简介--流简介
    java学习day12--API-SimpleDateFormat--BigDecimal/BigInteger类
    java学习day12--API-包装类-Date类
    equals方法和 == 的使用
    java学习day11--API--Object类-String类-StringBuilder类
    构造方法和普通方法的区别
    java中的修饰符总结
  • 原文地址:https://www.cnblogs.com/CSLaker/p/7281225.html
Copyright © 2011-2022 走看看