hugoquanlytauquoc

 avatar
quoc14
c_cpp
5 months ago
2.9 kB
3
Indexable
caidat
#include <iostream>

using namespace std;

int n;
int hoanvi[4];
int visit[4];
int ghe[100];
int oo = 1000000;
struct door {
	int pos;
	int num_pass;
};

door doors[300];
int ans;

void backtrack(int index, int total) {
	
	if (index == 4) {
		if (total < ans) {
			ans = total;
		}
		return;
	}
	
	int iddoor = hoanvi[index];
	
	int cur_pos = doors[iddoor].pos;
	int cur_numpass = doors[iddoor].num_pass;
	
	int left = cur_pos;
	int right = cur_pos;
	
	
	for (int i = 1; i <= cur_numpass - 1; i++) {
		// khi bang 0 la gap ghe trong se tra duoc ra vi tri ghe trong
		while (ghe[left] != 0 && left > 0) {
			left--;
		}
		
		while (ghe[right] != 0 && right <= n) {
			right++;
		}
		
		// neu ben trai het ghe
		if (left == 0) {
			ghe[right++] = iddoor;
			total += right - cur_pos;
			
			
		}
		// neu ben phai het ghe
		else if (right == n + 1) {
			ghe[left--] = iddoor;
			total += cur_pos - left;
			
			
		}
		else {
			
			if (cur_pos - left < right - cur_pos) {
				ghe[left--] = iddoor;
				total += cur_pos - left;
				
				
			}
			else {
				ghe[right++] = iddoor;
				total += right - cur_pos;
				
			}
			
		}
	}
	
	while (ghe[left] != 0 && left > 0) {
		left--;
	}
	while (ghe[right] != 0 && right <= n) {
		right++;
	}
	
	if (left == 0) {
		ghe[right++] = iddoor;
		total += right - cur_pos;
		backtrack(index + 1, total);
	}
	else if (right == n + 1) {
		ghe[left--] = iddoor;
		total += cur_pos - left;
		backtrack(index + 1, total);
	}
	else {
		if (cur_pos - left == right - cur_pos) {
				
			ghe[left] = iddoor;
			backtrack(index + 1, total + cur_pos - left + 1);
			ghe[left] = 0;
			ghe[right] = iddoor;
			backtrack(index + 1, total + right + 1 - cur_pos);
			
		}
		else if (cur_pos - left < right - cur_pos) {
			ghe[left--] = iddoor;
			total += cur_pos - left;
			backtrack(index + 1, total);
		}
		else if (cur_pos - left > right - cur_pos) {
			ghe[right++] = iddoor;
			total += right - cur_pos;
			backtrack(index + 1, total);
		}
		
		
	}
	
	for (int i = 1; i <= n; i++) {
		if (ghe[i] == iddoor) {
			ghe[i] = 0;
		}
	}
		
}

void back(int cua) {
	if (cua == 4) {
		backtrack(1, 0);
		return;
	}
		
	for (int i = 1; i <= 3; i++) {
		if (visit[i] == 0) {
			visit[i] = 1;
			hoanvi[cua] = i;
			back(cua + 1);
			visit[i] = 0;
		}
		
	}
	
	
	
	
	
	
}

void solve(int testcase) {
	
	cin >> n;
	
	for (int i = 1; i <= 3; i++) {
		cin >> doors[i].pos >> doors[i].num_pass;
	}
	ans = oo;
	back(1);
	
	cout << "Case #" << testcase << endl;
	cout << ans << endl;
	
	cout << "quoc" << endl;
	
	int tmp = 98;
	ghe[tmp++] = 5;
	cout << tmp << endl;
}




int main() {
	freopen("Text.txt", "r", stdin);
	int t; cin >> t;
	
	for (int i = 1; i <= t; i++) {
		solve(i);
	}
}
Leave a Comment