1. 程式人生 > >Extraordinarily Tired Students UVA

Extraordinarily Tired Students UVA

#include <iostream>
#include <string>
#include <set>

#define _for(i, a, b) for (int i = (a); i < (b); ++i)

using namespace std;

struct Stu {
	int A, B, C;
} stus[15];

set<string> es;

int n;

void encode (string & ans) {
	ans.clear();
	_for(i, 0, n)
		ans += (char)(stus[i].C + '0');
	return;
}

bool action(int kase, int t) {
	string e;
	encode(e);
	if (es.count(e)) {
		cout << "Case " << kase << ": -1" << endl;
		return true;
	}
	es.insert(e);

	int wake = 0, sleep = 0;
	_for(i, 0, n)
		if (stus[i].C <= stus[i].A)
			wake++;
	sleep = n - wake;

	if (sleep == 0) {
		cout << "Case " << kase << ": " << t << endl;
		return true;
	}

	_for(i, 0, n) {
		Stu & s = stus[i];
		s.C++;
		if (s.C == s.A + s.B + 1)
			s.C = 1;
		if (s.C == s.A + 1 && wake >= sleep)
			s.C = 1;
	}

	return false;
}

int main() {
	int k = 1;
	while (cin >> n && n) {
		es.clear();
		_for(i, 0, n)
			cin >> stus[i].A >> stus[i].B >> stus[i].C;
		int t = 1;
		while (true)
			if (action(k, t++))
				break;
		k++;
	}
	
	return 0;
}