#P6411. [COCI 2008/2009 #3] MATRICA

[COCI 2008/2009 #3] MATRICA

Description

You need to construct an n×nn \times n character matrix MM.

This character matrix must satisfy the following constraints:

  1. Mi,j=Mj,i (1i,jn)M_{i,j} = M_{j,i} \ (1 \le i,j \le n).
  2. It must contain exactly aia_i occurrences of the character cic_i.

Since there may be many valid constructions, you need to output the lexicographically smallest one.

Because the output would be too large, you only need to output pp columns. The exact requirement is stated in the Input Format.

If there is no solution, output IMPOSSIBLE.

Input Format

The first line contains two integers nn and kk, where kk is the number of constraints in constraint 2.

The next kk lines each contain an uppercase letter and an integer, which are cic_i and aia_i.

The next line contains an integer pp.

The next line contains pp integers, indicating the column indices you need to output, guaranteed to be in increasing order.

Output Format

Output an nn-row, pp-column character matrix. If there is no solution, output IMPOSSIBLE.

3 3
A 3
B 2
C 4
3
1 2 3 

AAB
ACC
BCC 

4 4
A 4
B 4
C 4
D 4
4
1 2 3 4 

AABB
AACC
BCDD
BCDD 
4 5
E 4
A 3
B 3
C 3
D 3
2
2 4 

AC
BE
DE
ED 

4 6
F 1
E 3
A 3
B 3
C 3
D 3
4
1 2 3 4 

IMPOSSIBLE 

Hint

Constraints

  • For 60%60\% of the testdata, n300n \le 300.
  • For 80%80\% of the testdata, n3×103n \le 3 \times 10^3.
  • For 100%100\% of the testdata, 1n3×1041 \le n \le 3 \times 10^4, 1k261 \le k \le 26, ai=n2\sum a_i = n^2, cicjc_i \neq c_j, 1p501 \le p \le 50.

Notes

This problem is translated from T4 MATRICA of Croatian Open Competition in Informatics 2008/2009 Contest #3.

Translated by ChatGPT 5