Link:
https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=3703
Title:
Given two alphabetic matrices of 6 rows and 5 columns, find a "password" that satisfies the following conditions: each letter in the password appears in the corresponding column of both matrices.
For example, the 2nd letter from the left must appear in the 2nd column from the left in both matrices.
Given k (1≤k≤7777), your task is to find the kth smallest lexicographical password. If not present, output NO.
analyze:
Classic decoding problem. First find all possible letters in each column of the answer, then decode bit by bit.
See the code for specific implementation.
Code:
1 import java.io.*; 2 import java.util.*; 3 4 public class Main { 5 static char G[][][] = new char[2][6][9]; 6 7 public static void main(String args[]) { 8 Scanner cin = new Scanner(new BufferedInputStream(System.in)); 9 10 int T = cin.nextInt(); 11 while(T --> 0) { 12 intk = cin.nextInt(); 13 cin.nextLine(); // clear buffer 14 for ( int t = 0; t < 2; t++ ) { 15 for ( int r = 0; r < 6; r++ ) { 16 G[t][r] = cin.nextLine().toCharArray(); 17 } 18 } 19 20 @SuppressWarnings("unchecked" ) 21 ArrayList<Character> a[] = new ArrayList[5]; // a [c]: All possible letters in column c of the answer 22 for (int i = 0; i < 5; i++) a[i] = new ArrayList<Character> (); 23 24 boolean has[][][] = new boolean [2][5][26]; // The first Is there a letter ch in column c of t matrices 25 for ( int c = 0; c < 5; c++ ) { 26 for ( int t = 0; t < 2; t++ ) { 27 for ( int r = 0; r < 6; r++ ) { 28 int ch = G[t][r][c] - 'A' ; 29 has[t][c][ch] = true ; 30 } 31 } 32 for(int i = 0; i < 26; i++) 33 if(has[0][c][i] && has[1][c][i]) a[c].add((char)(i+'A')); 34 } 35 36 int up = 1; 37 for(int i = 0; i < 5; i++) up *= a[i].size(); 38 if(k > up) { 39 System.out.println("NO"); 40 continue; 41 } 42 43 k--; // 解码 44 for(int i = 0; i < 5; i++) { 45 up /= a[i].size(); 46 System.out.print(a[i].get(k/up)); 47 k %= up; 48 } 49 System.out.println(); 50 } 51 cin.close(); 52 } 53 }