#include "triangles.h"

#include <vector>
using namespace std;

bool isIn(Triangle t, int h) {
    Triangle t3 = {t.i, t.j, t.k};
    Triangle t1 = {t.i, t.k, h};
    Triangle t0 = {t.j, t.k, h};
    Triangle t2 = {t.i, t.j, h};
    if (compare({t1, t2, t0}, {t3}) == 0) {
        return true;
    }
    return false;
}

bool isConv(Triangle t, int i) {
    Triangle t1 = {t.i, t.k, i};
    Triangle t2 = {t.j, t.k, i};
    Triangle t3 = {t.i, t.j, i};
    if (compare({t, t1}, {t2, t3}) == 0) {
        return true;
    }
    return false;
}

std::vector<std::vector<int>> solve(int n) {
    vector<int> hull = {0, 1, 2};
    for (int h = 3; h < n; h++) {
        vector<int> used(n);
        for (int l = 0; l < hull.size(); l++) {
            if (hull.size() == 2) {
                break;
            }
            Triangle t = {hull[(l + hull.size() - 1) % hull.size()], h, hull[(l + 1) % hull.size()]};
            if (isIn(t, hull[l])) {
                used[l] = -1;
            }
        }
        vector<int> hull1;
        int idx = -1;
        for (int i = 0; i < hull.size(); i++) {
            if (used[i] == -1) {
                if (idx == -1) {
                    hull1.push_back(h);
                    idx = i;
                }
            } else {
                hull1.push_back(hull[i]);
            }
        }
        swap(hull, hull1);
        if (idx == -1) {
            bool flag = true;
            for (int i = 2; i < hull.size(); i++) {
                Triangle t = {0, hull[i - 1], hull[i]};
                if (isIn(t, h)) {
                    flag = false;
                    break;
                }
            }
            if (flag) {
                for (int i = 0; i < hull.size(); i++) {
                    flag = true;
                    Triangle t = {hull[i], hull[(i + 1) % hull.size()], h};
                    for (int j = 0; j < hull.size(); j++) {
                        if (j == i || j == (i + 1) % hull.size()) {
                            continue;
                        }
                        if (!isConv(t, hull[j])) {
                            flag = false;
                            break;
                        }
                    }
                    if (flag) {
                        idx = (i + 2) % hull.size();
                        break;
                    }
                }
            }
            hull1.clear();
            for (int i = 0; i < hull.size(); i++) {
                if (i == idx) {
                    hull1.push_back(h);
                }
                hull1.push_back(hull[i]);
            }
            swap(hull, hull1);
        }
    }
    vector<vector<int> > ans;
    for (int i = 2; i < hull.size(); i++) {
        ans.push_back({hull[0], hull[i - 1], hull[i]});
    }
    return ans;
}
