zoukankan      html  css  js  c++  java
  • poj 3187 Backward Digit Sums(暴力)

    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.
    题意:给出排列1-n的范围n和要得到的m,问字典序最小的排列方式。
    思路:用next_permutation函数进行全排列,对于每个排列进行计算直到得到和为m时结束。打印此时得到的排列结果
    AC代码:
     1 #include <iostream>
     2 #include<cstdio>
     3 #include <cstring>
     4 #include <queue>
     5 #include<algorithm>
     6 using namespace std;
     7 
     8 int main()
     9 {
    10     long long n,m;
    11     long long a[15],b[15];
    12     while(~scanf("%lld%lld",&n,&m))
    13     {
    14         for(int i=0; i<n; i++)
    15             a[i]=i+1;
    16         while(1)
    17         {
    18             for(int i=0; i<n; i++)
    19                 {
    20                     b[i]=a[i];
    21                 }
    22             int flag=n;
    23             while(flag!=1)
    24             {
    25                 for(int i=0; i<flag; i++)
    26                     b[i]=b[i]+b[i+1];
    27                 flag--;
    28             }
    29             if(b[0]==m)
    30             {
    31                 for(int i=0; i<n-1; i++)
    32                     printf("%lld ",a[i]);
    33                 printf("%lld
    ",a[n-1]);
    34                 break;
    35             }
    36             next_permutation(a,a+n);
    37         }
    38     }
    39     return 0;
    40 }
    View Code
  • 相关阅读:
    一周总结
    各个方法的不同和优缺点
    随机抽签程序报告
    一周总结
    一周总结
    一周总结
    数据库基本知识
    线程相关概念
    进程相关概念
    模拟ssh实现远程执行命令(socket)
  • 原文地址:https://www.cnblogs.com/wang-ya-wei/p/6212832.html
Copyright © 2011-2022 走看看