#include using namespace std; const int maxN = 600; const int cLimit = 256; struct Color{ int r; int b; int g; }; clock_t startTim; int h, w; pair c[3][cLimit + 10]; Color a[maxN][maxN], b[maxN][maxN], rez[maxN][maxN]; Color paleta[20], curPaleta[20], bestPaleta[20]; int tip[maxN][maxN]; int t; long long bestAns; mt19937 rng(time(0)); double currentTim() { clock_t now = clock(); return 1.00*(now- startTim) / CLOCKS_PER_SEC; } void read_data() { freopen("imrec.in", "r", stdin); cin>>t; if (t==1) { for (int i = 0 ;i<16;i++) cin>>paleta[i].r>>paleta[i].b>>paleta[i].g; } scanf("%d%d",&w,&h); if (t==0){ for (int i =1;i<=h;i++) for(int j =1;j<=w;j++) scanf("%d%d%d",&a[i][j].r,&a[i][j].b,&a[i][j].g); } else { for (int i=1;i<=h;i++) for (int j=1;j<=w;j++) scanf("%d",&tip[i][j]); } fclose(stdin); } int dist(Color a, Color b) { return (a.r - b.r) *(a.r - b.r) + (a.b - b.b)*(a.b - b.b) + (a.g - b.g)*(a.g - b.g); } long long score() { long long ans = 0; for (int i = 1;i<=h;i++) for (int j=1;j<=w;j++) ans+=dist(a[i][j], b[i][j]); return ans; } void swapRez() { for (int i =1;i<=h;i++) for (int j = 1;j<=w;j++) rez[i][j] = b[i][j]; for (int i = 0; i< 16;i++) bestPaleta[i] = curPaleta[i]; } void print_data() { freopen("imrec.out", "w", stdout); if (t==0) { for (int i = 0;i<16;i++) printf("%d %d %d\n",bestPaleta[i].r, bestPaleta[i].b,bestPaleta[i].g); } else { for (int i = 1;i<=h;i++){ for (int j = 1;j<=w;j++) printf("%d %d %d ", rez[i][j].r, rez[i][j].b, rez[i][j].g); printf("\n"); } } fclose(stdout); } void decode() { for (int i = 1;i<=h;i++){ for (int j = 1;j<=w;j++) rez[i][j] = paleta[tip[i][j]]; } } void najbliza() { for (int i =1;i<=h;i++) for (int j=1;j<=w;j++) b[i][j] = curPaleta[0]; for (int i=1;i<=h;i++) for (int j=1;j<=w;j++) for (int l = 0 ; l<16;l++) if (dist(a[i][j], curPaleta[l]) < dist(a[i][j], b[i][j])) { b[i][j] = curPaleta[l]; } } void encode() { bestAns = 1e18; for (int i =0 ;i<256;i++){ c[0][i] = {0,i }; c[1][i] = {0, i}; c[2][i] = {0, i}; } for (int i=1;i<=h;i++) for (int j=1;j<=w;j++){ for (int l = 0; l< 256;l++){ c[0][l].first+= (l - a[i][j].r)*(l -a[i][j].r); c[1][l].first+= (l - a[i][j].b)*(l -a[i][j].b); c[2][l].first+= (l - a[i][j].g)*(l -a[i][j].g); } } sort(c[0], c[0] + 256); sort(c[1], c[1] + 256); sort(c[2], c[2] + 256); for (int i =0;i<16;i++) curPaleta[i] = {c[0][i].second, c[1][i].second, c[2][i].second}; najbliza(); long long currentScore = score(); if (currentScore < bestAns) { bestAns = currentScore; swapRez(); } } int main(){ startTim = clock(); read_data(); if (t == 1) decode(); else encode(); print_data(); }