[HDU] [1716] Permutation 2

Problem Description

Loading...

Problem Analysis

A problem about outputting permutation and combination results
At first I forgot the function in C++…
So I wrote it the hard way

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include<stdio.h>
#include<algorithm>
using namespace std;
int x[10000];
int main() {
	int a[4];
	bool kaseflag=false;
	while(scanf("%d %d %d %d",&a[0],&a[1],&a[2],&a[3]),a[0]||a[1]||a[2]||a[3]) {
		if(kaseflag)
			printf("\n");
		sort(a,a+4);
		for(int i=0; i<4; i++) {
			bool flag=false;
			int ti=a[i];
			for(int j=0; j<4; j++) {
				if(j!=i) {
					int tj=ti*10+a[j];
					for(int k=0; k<4; k++) {
						if(k!=i&&k!=j) {
							int tk=tj*10+a[k];
							for(int p=0; p<4; p++) {
								if(p!=i&&p!=j&&p!=k) {
									int tp=tk*10+a[p];
									if(tp<1000)
										continue;
									if(!x[tp]) {
										x[tp]=1;
										if(flag)
											printf(" %d",tp);
										else
											printf("%d",tp);
										flag=true;
									}
								}
							}
						}
					}
				}
			}
			if(flag)
				printf("\n");
		}
		kaseflag=true;
	}
	return 0;
}

Then I wrote another C++
next_permutation
version

Note that when using this function, you need to ensure the initial array is already sorted in ascending order
(The problem statement doesn’t say this, but the test data should all be already sorted)

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include<stdio.h>
#include<algorithm>
using namespace std;
int main() {
	int a[4];
	bool kaseflag=false;
	while(scanf("%d%d%d%d",&a[0],&a[1],&a[2],&a[3]),a[0]||a[1]||a[2]||a[3]) {
		sort(a,a+4);
	//无意中发现 如果不排序会出BUG	
	//不排序错误数据
	//3 6 8 4
	//3 8 4 6
	//……等等 
		if(kaseflag)
			printf("\n");
		int t;
		bool flag=true;
		do {
			if(a[0]==0)
				continue;
			if(flag) {
				printf("%d%d%d%d",a[0],a[1],a[2],a[3]);
				flag=false;
			} else if(t==a[0])
				printf(" %d%d%d%d",a[0],a[1],a[2],a[3]);
			else
				printf("\n%d%d%d%d",a[0],a[1],a[2],a[3]);
			t=a[0];
		} while(next_permutation(a,a+4));
		printf("\n");
		kaseflag=true;
	}
	return 0;
}

Problem link: 【杭电】[1716]排列2

This post is licensed under CC BY-NC-SA 4.0. If it helped, or if you have anything to say, the comment box below is open.
Page views —
Unique visitors —

Loading...