Original title link P1706 full array problem
Title Description
repeated any number of digital output sequence of natural numbers 1 to n are arranged all distinct, i.e., n whole arrangement requires the generated allowed.
Input Output Format
Input Format:
n-(1≤n≤9)
Output format:
all distinct from the sequence of numbers 1 ~ n consisting of a sequence of each row. Each number 5 Reserved often wide.
Sample input and output
Input Sample # 1:
3
Output # 1 Sample:
1 2. 3
1 2. 3
2. 3 1
2 1. 3
. 3 1 2
. 3 2 1
answer
Subject has no difficulty (if these words hurt you, sorry, my fault), silent people is the result of output format
Output card here several times WA
Here it is recommended that output printf
printf(“%5d”,&a[i])
The output format in the wrong here.
Or simply talk about DFS depth-first search, do not understand the small partners recommend a look at Aha Lei book, "Aha! Algorithm ", written in a very easy to understand, and very interesting for a beginner like me basin faithful.
1-9 1-9 nine number nine is like playing cards, like the array box.
Nine a few too many, here I took Examples 1-3
Corresponding to the start of each cassette into poker, it is 123
The first four boxes went there found no poker hands, and to go back to pick up No. 3 inside the box 3, there is no other hand it was only 3 numbers, so had to continue to go back; went to No. 2 Pick up the box 2, 2 and 3, then hands alone have been let go, put 3 into them, and then go backwards, into the No. 3 box 2. Is 132
Next, following the procedure of simulation earlier, will generate all first sequences
2 1 3
2 3 1
3 1 2
3 2 1
Source code is as follows:
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
void dfs(int step);
int a[10],book[10],n;
void dfs(int step)
{
int i;
if(step==n+1)
{
for(i=1;i<=n;i++)
printf("%5d",a[i]);
// cout<<" "<<a[i];
cout<<endl;
return ;
}
for(i=1;i<=n;i++)
{
if(book[i]==0)
{
a[step]=i;
book[i]=1;
dfs(step+1);
book[i]=0;
}
}
return ;
}
int main()
{
cin>>n;
dfs(1);
// getchar();getchar;
return 0;
}
If the basin faithful understand and master, you can try to use dfs address the following issues:
P1008 trifecta
P1618 trifecta (upgrade version)
try to solve problems in different ways, the problem can give you a profit is not the same .
Novice, I hope Daniel exhibitions, a lot of criticism; what problems can be more exchanges
Here is my valley in Los blog, welcome to visit
Luogu Bo-off
My name is Mario, a determined program to be admitted to MIT ape