View Code of Problem 10

#include <iostream>
using namespace std;

int arr[4];  // 存储输入的一行数据

int main() {
    int t;
    cin >> t;
    while (t--) {
        for (int i = 0; i < 4; i++) {
            cin >> arr[i];
        }

        bool flag = false;  // 是否有数字相同
        bool combined[4] = {false};  // 数字是否已经合并
        for (int i = 3; i > 0; i--) {  // 从右往左扫描
            if (arr[i] == 0) {  // 当前位置没有数字
                continue;
            }
            for (int j = i - 1; j >= 0; j--) {  // 找到相邻的数字
                if (arr[j] == 0) {
                    continue;
                } else if (arr[j] == arr[i]) {  // 相邻数字相同
                    arr[i] *= 2;
                    arr[j] = 0;
                    combined[i] = true;
                    flag = true;
                    break;
                } else {  // 相邻数字不同
                    break;
                }
            }
        }

        // 向右靠
        for (int i = 0, k = 3; i <= 3; i++) {
            if (arr[i] != 0) {
                if (combined[k]) {
                    combined[k] = false;
                } else {
                    k--;
                }
                arr[k] = arr[i];
            }
        }
        while (k >= 0) {
            arr[k--] = 0;
        }

        // 输出结果
        for (int i = 0; i < 4; i++) {
            cout << arr[i] << " ";
        }
        cout << endl;
    }
    return 0;
}
/*
Main.cc: In function 'int main()':
Main.cc:46:16: error: 'k' was not declared in this scope
         while (k >= 0) {
                ^
*/

Double click to view unformatted code.


Back to problem 10