Baidu interview questions -- find next permuation, poj 1883)

Source: Internet
Author: User

During the interview, questions about sorting were quite common. I had a problem with Baidu and shared it.

Description:

Here is an array. If it is sorted by the number size, what is the next arrangement of the current array?

For example, the following data is the four groups of data generated in order.

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

Baidu I found that there is an identical question on poj: http://poj.org/problem? The id = 1833.

Although there is a function called next_permutation, but it's okay to do OJ, the interview is definitely not good, so I should analyze it myself.

Analysis:

We use the lexicographically arranged generation method:

Generate the next arrangement for the given full Arrangement

The so-calledNext of oneYesThisAnd

NextBetweenNo other. This requires that this one and the next are as much as possible.LongOfCommon prefix, That is, the change limit is as much as possibleShortOfSuffix.


The algorithm consists of three steps:

In general, Set P to a full arrangement of [1, N.

1. P = P1P2... Pn = P1P2... Pj-1PjPj + 1... Pk-1PkPk + 1... Pn

J = max {I | pI <PI + 1}, K = max {I | pi> PJ}

2. Switch PJ, PK, and PJ + 1... Pk-1PjPk + 1... Pn flip,

3. P' = P1P2... Pj-1PkPn... PK + 1pjpk-1... PJ + 1 is the next of P.

The Code is as follows:

Memory: 168KTime: 469MSLanguage: C++Result: AcceptedSource Code#include<stdio.h>#include <memory.h>void swap( int &a, int &b){a = a ^ b;b = a ^ b;a = a ^ b;}bool GetNextPermutation(int a[], int size){int m = size - 1;int i,j;while(m > 0 && a[m-1] > a[m]) // step 1{m--;}//in this case, the current permutation is the lastif(m == 0) //{for( i = 0, j = size - 1; i < j; i++, j--){swap(a[i], a[j]);}return false;}for( j = size - 1; j > m - 1; j--)//step 2{if(a[j] > a[m-1]){swap(a[j], a[m-1]);break;}}for( i = m, j = size - 1; i < j; i++, j--)//step 3{swap(a[j], a[i]);}return true;}void printArray(int a[], int size){int i;for( i = 0; i < size; i++){ if( i == 0){printf("%d", a[i]);}else{printf(" %d", a[i]);}}printf("\n");}int main(){int nSize;int a[1024];int ncase;scanf("%d", &ncase);int n,k;while(ncase--){scanf("%d%d", &n, &k);for( int i = 0; i < n; i++){scanf("%d", &a[i]);}while(k--){GetNextPermutation(a, n);}printArray(a, n);}return 0;}

However, since we have mentioned how to find rehearsals, we will also provide a method to generate all the permutation. It is the "Exchange Method" in the combination of mathematics"

The process for running this method is as follows:

Consider {1, 2... N} is an arrangement in which each integer is given a direction, which is called an integer.KMobile & active, if the adjacent point in the direction indicated by its arrow is smaller than itself. For example

In, 6, 3, and 5 are movable. Obviously, 1 can never be moved. N can be moved except in the following two cases:

(1) n is the first number and points to the left

(2) n is the last number and points to the right.

Therefore, we can

Generate all arrays according to the following algorithm

Algorithm

1. Start:


2. When there is a number to be transferred

(A) Find the largest number of convertible M (B) Change m and the adjacent number indicated by the arrow (c) to adjust the direction of the resulting number P in the order greater than M, that is, change to the opposite direction.
The Code is as follows:
# Include <stdio. h> # include <memory. h> Enum direction {left, right}; // enumerate struct num in one direction // each number has a direction and value {direction D; int value ;}; num permutation [100]; // if return value is-1, it means we can't find the permutation anymoreint getfirstmoveable (INT nsize) // find the maximum number that can be moved in all numbers, returns the subscript {int maxvalue = 0; int idx =-1; for (INT I = 0; I <nsize; I ++) {if (I = 0 & permutation [I]. D = left) // leftmost, and the moving direction is left {continue;} if (I = Nsize-1 & permutation [I]. D = right) // rightmost, and moves to the right {continue;} If (permutation [I]. D = left) // if the direction is left and it is larger than the left element, {If (permutation [I]. value> permutation [I-1]. value) {If (maxvalue <permutation [I]. value) {maxvalue = permutation [I]. value; idx = I ;}} else {If (permutation [I]. value> permutation [I + 1]. value) // to the right, larger than the right {If (maxvalue <permutation [I]. value) {maxvalue = permutation [I]. value; idx = I ;}}} return idx ;} Void reversedirection (int r, int nsize) // after the switch is complete, all directions greater than the value currently exchanged are reversed {for (INT I = 0; I <nsize; I ++) {If (permutation [I]. value> permutation [R]. value) {If (permutation [I]. D = left) {permutation [I]. D = right;} else {permutation [I]. D = left ;}}} void swap (Num & A, num & B) {num T = A; A = B; B = T;} void swapvalue (INT R, int & nr) // exchange adjacent values {If (permutation [R]. D = left) {swap (permutation [R], permutation [r-1]); Nr = R-1 ;}else {swap (permutation [R], permutation [R + 1]); Nr = R + 1 ;}} void printall (INT nsize) {for (INT I = 0; I <nsize; I ++) {printf ("% d", permutation [I]. value);} printf ("\ n");} int main () {int N; while (scanf ("% d", & N )! = EOF) {for (INT I = 0; I <n; I ++) {permutation [I]. value = I + 1; permutation [I]. D = left;} int R; int NR; printall (n); While (r = getfirstmoveable (N ))! =-1) // algorithm core loop {swapvalue (R, NR); reversedirection (NR, n); printall (n) ;}} return 0 ;}





 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.