Violence algorithm: array generator

1. The arrangement 1 to n generates the
idea:
introducing cur (cur currently determined first number) to (cur + 1) recursive manner;
Note:
1) the position of the recursive function;.
Code:

#include<cstdio>
#include<iostream>
using namespace std ;

void print_permutation ( int n , int *A , int cur ) {
 if ( cur == n ) {
  for ( int i = 0 ; i < n ; i ++ ) printf("%d",A[i]) ;
  printf("\n") ;  //
 }
 else {
  for ( int i = 1 ; i <= n ; i ++ ) {
   int ok = 1 ;
   for ( int j = 0 ; j < cur ; j ++ ) {
    if ( A[j] == i ) {
     ok = 0 ;
     break ;
    }
   }
   if ( ok == 1 ) {
    A[cur] = i ;
    print_permutation ( n , A , cur + 1 ) ;
   }   
  }  
 }
} 

int main() {
 int n , A[100];
 cin>>n ;
 for ( int i = 0 ; i < n ; i ++ ) A[i] = i + 1 ;
 print_permutation ( n , A , 0 ) ;
 return 0 ;
}

2. Generate a predetermined arrangement of array P (re-set)
ideas:
1) P is calculated contains P [i] of number c1, cur-1 th frequency is calculated comprising P [i] of A front c2, comparison, if c1 is greater than c2, the P [i] Alternatively still, through the entire array when P a [cur] each selection;
2) encountered when P [i] = P [i - 1] case, the whole is not performed. it as the beginning of the process.
Such as P = {1,1,1}, if are executed, output 3 . 3 3 = 27 {1,1,1}; performing only the first, output a {1,1,1}, the first cycle, pick the first one, the second cycle, pick the first one, the third cycle, pick the first one; (re-set function when the operation is first number)
Code:

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std ;

void print_permutation ( int n , int *P , int *A , int cur ) {
 if ( cur == n ) {
  for ( int i = 0 ; i < n ; i ++ ) printf("%d",A[i]) ;
  printf("\n") ; 
 }
 else {
  for ( int j = 0 ; j < n ; j ++ ) 
  if ( j == 0 || P[j] != P[j - 1] ) {
   int c1 = 0 , c2 = 0 ; 
   for ( int i = 0 ; i < n ; i ++ ) {
    if ( P[j] == P[i] ) c1 ++ ;
   } 
   for ( int i = 0 ; i < cur ; i ++ ) {
    if ( A[i] == P[j] ) c2 ++ ;
   }
   if ( c1 > c2 ) {
    A[cur] = P[j] ;
    print_permutation ( n , P , A , cur + 1 ) ;
   }
  }
 }
} 

int main() {
 int n ;
 cin>>n ;
 int P[n] , A[n] ;
 for ( int i = 0 ; i < n ; i ++ ) scanf("%d",&P[i]) ;
 print_permutation ( n , P , A , 0 ) ;
 return 0 ;
}

3. The next arrangement: next_permutation ()
Code:

#include<cstdio>
#include<algorithm>
using namespace std ;

int main() {
 int n ;
 scanf ( "%d",&n ) ;
 int p[n] ;
 for ( int i = 0 ; i < n ; i ++ ) scanf ( "%d", &p[i] ) ;
 sort ( p , p + n ) ;
 do {
  for ( int i = 0 ; i < n ; i ++ ) printf ( "%d",p[i] ) ;
  printf ( "\n" ) ;
 } while ( next_permutation( p , p + n ) ) ;
 return 0 ;
}
Released two original articles · won praise 0 · Views 34

Guess you like

Origin blog.csdn.net/QQQ899/article/details/104679076