Informatics Orsay Yitong 1317: [Example 5.2] Combined output search dfs and backtracking

1317: [Example 5.2] Combined output

Time limit: 1000 ms Memory limit: 65536 KB
Commitments: 13575 Passes: 6581
[Title description]
Arrangement and combination is a commonly used mathematical method, in which combination is to extract r elements from n elements (no order and r≤ n), we can simply understand n elements as natural numbers 1, 2, ..., n, and take any r number from them.

Now you are required to output all combinations in a recursive way.

For example, n = 5, r = 3, all combinations are:

1 2 3 1 2 4 1 2 5 1 3 4 1 3 5 1 4 5 2 3 4 2 3 5 2 4 5 3 4 5

[Input]
Two natural numbers n and r in a line (1 <n <21, 1≤r≤n).

[Output] For
all combinations, each combination occupies a row and the elements in it are arranged in ascending order, each element occupies three characters, and all combinations are also in dictionary order.

[Sample input]
5 3
[Sample output]
1 2 3
1 2 4
1 2 5
1 3 4
1 3 5
1 4 5
2 3 4
2 3 5
2 4 5
3 4 5


Use array b to determine whether the number at that position has been used, and use a [k] to store the determined number.
For example, output 1 2 4
a [1] = 1, a [2] = 2, a [3] = 4
b [1] = 1, b [2] = 1, b [4] = 1

Baba did not understand at first, how to use dfs here, and then the child told Baba how to understand.

The key is the first loop in the code dfs, if you follow the example of a book (page 245, the original book is for int i = 1;, now it is for int i = a [k-1] +1;), print It comes out not only from small to large, but also contains 5 4 3 like this from large to small numbers.

Like the child.


#include<bits/stdc++.h>
#define N 22
using namespace std; 
int num=0,a[10001]={0},n,r;
bool b[10001]={0};
int dfs(int);
int print();
int main(){
	freopen("cpp.in","r",stdin);
	freopen("cpp.out","w",stdout);
    cin>>n>>r; 
    dfs(1);
    return 0;
}
int dfs(int k){
	int i;
	for(i=a[k-1]+1;i<=n;i++){
		if(!b[i]){
			a[k]=i;
			b[i]=1;
			if(k==r){
				print();
			}
			else {
				dfs(k+1);
			}
			b[i]=0;
		}
	}
}
int print(){
	num++;
	for(int i=1;i<=r;i++){
		cout<<setw(3)<<a[i];
	}
	cout<<endl;
}
Posted 33 original articles · liked 0 · visits 167

Guess you like

Origin blog.csdn.net/weixin_42790071/article/details/105530215