The small constraints make Bruteforce/Exhaustive Search feasible, and it's trivial to take the best of the rest. #include <iostream> #include <algorithm> #include <cstdio> using namespace std; int main() { int perm[] = {0, 1, 2}; int index[] = {0, 1, 2}; int data[9]; int sum[3]; int move; int max; // freopen("102.txt", "r", stdin); while(cin >> data[0] && data[0] != EOF) { for(int i=1; i<9; i++) cin >> data[i]; for(int i=0; i<3; i++) sum[i] = 0; for(int i=0; i<3; i++) for(int j=0; j<3; j++) sum[i]+=data[i+j*3]; max = sum[0] + sum[1] + sum[2]; do { move = 0; for(int i=0; i<3; i++) { if(perm[i] == 0) // 'B' move = move + sum[0] - data[i*3]; else if(perm[i] == 1) // 'C' move = move + sum[2] - data[i*3+2]; else if(perm[i] == 2) // 'G' move = move + sum[1] - data[i*3+1]; } if(move < max) { max = move; for(int i=0; i<3; i++) index[i] = perm[i]; } } while(next_permutation(perm, perm+3)); for(int i=0; i<3; i++) { if(index[i] == 0) putchar('B'); else if(index[i] == 1) putchar('C'); else putchar('G'); } cout << ' ' << max << endl; } return 0; }