Blue Bridge Cup---Arrangement Problem---Full Arrangement

test question algorithm training permutation problem

Resource constraints

Time limit: 1.0s Memory limit: 512.0MB

Problem Description

  Find a permutation of 0 to N-1 (that is, each number can only appear once), and give the constraints (a N*N table, 1 or 0 in the i-th row and the j-th column, expressed as j-1 this The number cannot appear after the number i-1, and it is guaranteed that the i-th row and the i-th column are 0). Consider this arrangement as a natural number, and find the K-th arrangement from small to large.

Data size and conventions

  N<=10,K<=500000

input format

  The first line is N and K, the next N lines, each line has N numbers, 0 means not, 1 means can

output format

  the desired arrangement

sample input

3 2
0 1 1
1 0 0
0 1 0

Sample output

1 0 2
Explanation:
For the case of N=3 without any restrictions
First: 0 1 2
Second: 0 2 1
Third: 1 0 2
Fourth: 1 2 0
Fifth: 2 0 1
Sixth: 2 1 0
According to the constraints given by the title, since 2 cannot appear after 1, 0 cannot appear after 2.
First: 0 2 1
Second: 1 0 2
Third: 2 1 0

implementation code

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

int n, k, cnt = 0;
int arr[10], vis[10][10];

bool Judge() {
    
    
	for(int i = 1; i< n; i++) if (!vis[arr[i - 1]][arr[i]]) return false;
	return true;
}

int main() {
    
     
	cin >> n >> k;
	for (int i = 0; i < n; i++) arr[i] = i;
	for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) cin >> vis[i][j];
	do {
    
    
		if (Judge()) if (++cnt == k) break;
	} while (next_permutation(arr, arr + n));
	for (int i = 0; i < n; i++) {
    
    
		if (i) cout << " ";
		cout << arr[i];
	}
	cout << endl;
	return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325687744&siteId=291194637