Untitled
#include <iostream> using namespace std; int a[62], n, kh[4][2], res; bool c[4]; void reset() { for (int i = 1; i <= n; i++) { a[i] = 0; } for (int i = 1; i <= 3; i++) { c[i] = false; } } void sitdown(int door, int &left, int &right) { int count = kh[door][1]; int id = kh[door][0]; if (a[id] == 0) { a[id] = door; count--; } while (count > 1) { if (left >= 1 && count > 1) { if (a[left] == 0) { a[left] = door; count--; } left--; } if (right <= n && count > 1) { if (a[right] == 0) { a[right] = door; count--; } right++; } } } void sitLeft(int door, int &left) { while (left >= 1) { if (a[left] == 0) { a[left] = door; break; } else { left--; } } } void sitRight(int door, int &right) { while (right <= n) { if (a[right] == 0) { a[right] = door; break; } else { right++; } } } void unset(int door) { for (int i = 1; i <= n; i++) { if (a[i] == door) a[i] = 0; } } void print() { for (int i = 1; i <= n; i++) { cout << a[i] << " "; } cout << endl; } int calculator() { int sum = 0; for (int i = 1; i <= n; i++) { if (a[i] != 0) { int v = kh[a[i]][0]; if (v > i) sum += (v - i) + 1; else sum += (i - v) + 1; } } return sum; } void backtrack(int count) { if (count == 3) { /*print();*/ int result = calculator(); /*cout << result << endl;*/ if (result < res) res = result; } for (int i = 1; i <= 3; i++) { if (!c[i]) { c[i] = true; int left = kh[i][0] - 1; int right = kh[i][0] + 1; sitdown(i, left, right); sitLeft(i, left); if (a[left] == i) { backtrack(count + 1); a[left] = 0; } sitRight(i, right); if (a[right] == i) { backtrack(count + 1); a[right] = 0; } unset(i); c[i] = false; } } } void solve(int index) { cin >> n; res = 100000; reset(); for (int i = 1; i <= 3; i++) { cin >> kh[i][0] >> kh[i][1]; } /*int left = kh[1][0] - 1; int right = kh[1][0] + 1; sitdown(1, left, right); sitLeft(1, left); sitRight(1, right); cout << right << endl; print();*/ backtrack(0); cout << res << endl; } int main() { int t; cin >> t; for (int i = 1; i <= t; i++) { solve(i); } }
Leave a Comment