USACO2006 Backward Digit Sums /// 全排列 oj24212
题目大意:
给出杨辉三角的顶点值M和底边数的个数 N (1 ≤ N ≤ 10) ,求出底边各个数的值,其中各个数范围都为1 ~ N
当N=4,M=16时可能是这样的
3 1 2 4
4 3 6
7 9
16
Input
Multiple test cases. For each case:
* Line 1: Two space-separated integers: N and the final sum.
Output
For each case, output one line : 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.
3 1 2 4不是唯一解, 但是按字典序的最小解
N较小 直接暴力 用next_permutation()全排列函数 得出下一种排列 验证正确则跳出结束
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include <bits/stdc++.h> using namespace std; int a[15],b[15],n,m; bool judge() { for(int k=n;k>1;k--) { for(int i=1;i<k;i++) b[i]=b[i]+b[i+1]; } if(b[1]==m) return 1; else return 0; } void per() { do { for(int i=1;i<=n;i++) b[i]=a[i]; if(judge()) return; }while(next_permutation(a+1,a+1+n)); } int main() { while(~scanf("%d%d",&n,&m)) { for(int i=1;i<=n;i++) a[i]=i; per(); for(int i=1;i<n;i++) printf("%d ",a[i]); printf("%d\n",a[n]); } }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步