Saturday, June 6, 2015

UVa 161 - Traffic Lights

// UVa 161 - Traffic Lights

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

struct ev {
	int time;
	int light;
	int turn;
};

bool operator <(const ev & a, const ev & b) {
	return a.time < b.time;
}

int main() {
	do {
		vector<ev> v;
		int a;
		cin >> a;
		if (a == 0)
			break;
		int n = 0;
		while (a != 0) {
			// store all events
			ev e = { 0, n, true };
			while (e.time <= 18000) {
				ev f = { e.time + a - 5, e.light, false };
				v.push_back(f);
				e.time += a + a;
				v.push_back(e);
			}
			// read next light
			cin >> a;
			n++;
		}
		// sort by time
		sort(v.begin(), v.end());
		// turn lights on/off
		int ons = n, sol = -1;
		for (int i = 0; i < v.size(); i++) {
			if (i == 0 || v[i].time == v[i - 1].time || ons < n)
				ons += (v[i].turn ? 1 : -1);
			else {
				sol = v[i - 1].time;
				break;
			}
		}
		// output
		if (sol == -1)
			cout << "Signals fail to synchronise in 5 hours" << endl;
		else {
			int h = sol / 3600;
			int m = (sol % 3600) / 60;
			int s = sol % 60;
			cout << "0" << h << ":" << m / 10 << m % 10 << ":" << s / 10 << s % 10 << endl;
		}
	} while (true);
	return 0;
}

No comments:

Post a Comment