题意:传送门
题目描述
As you know, shadow95 is pretty good at maths, especially combinatorial mathematics. Now, he has made a problem for you. We call a subset which exactly has r elements as a "r-subset".For example, {1,2,5} is a 3-subset(r=3) of {1,2,3,4,5}. Now, your task is to form all the r-subset of {1,2,...,n}, then output them in lexicographic order(字典序).
输入
The input file ends by EOF.
For each test case, there are two integer n,r.(1 <= r < n <= 20)
输出
First output the case number, then output all the r-subset of {1,2,...,n} in lexicographic order.
Each case seperates by a blank line.
示例输入
3 2 3 1
示例输出
Case #1: 1 2 1 3 2 3 Case #2: 1 2 3题目很简单,代码很快就敲出来了,令人伤心的是PE无数遍,因为之前的题都没卡那么严,遇到这种输出格式错误慌了.......每组数据之后有一个空行,但是最后一组数据没有空行,如果只输入一组n,m,那么之后不需要打印空行。具体请看代码:
#include <iostream> #include <algorithm> #include <math.h> #include <map> #include <queue> #include <stack> #define inf 0x3f3f3f3f #include <stdio.h> #include <string.h> typedef long long ll; #define mod 10000007 #define eps 1e-9 using namespace std; int n,r,a[30]; void dfs(int k,int step) { a[step]=k; if(step>r) return ; if(step==r) { for(int i=1; i<=step; i++) { if(i==1) printf("%d",a[i]); else printf(" %d",a[i]); } printf("\n"); } for(int i=k+1; i<=n; i++) dfs(i,step+1); } int main() { int K=0; while(scanf("%d%d",&n,&r)!=EOF) { if(K>=1) printf("\n");//这样能避免PE printf("Case #%d:\n",++K); for(int i=1; i<=n-r+1; i++) dfs(i,1); } return 0; }
时间: 2024-10-11 12:48:24