首页 > 代码库 > UVA 467 - Synching Signals(数论)

UVA 467 - Synching Signals(数论)

UVA 467 - Synching Signals

题目链接

题意:给定几个红绿灯,每个红绿灯time表示,time秒红灯,time - 5秒绿灯, 5秒黄灯.
然后求全部灯变绿之后,在一次有灯变换之后,全是绿灯需要的时间

思路:由于只要算1小时,也就是3600秒,直接暴力过去,每次时间加上当前最小能变换灯的时间,然后记录一下每个灯的颜色状态,直到全变绿为止

代码:

#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;

char str[105];
int ti[15], s[15], r[15], n;
int cas = 0;

void solve() {
	int k = ti[0];
	//s = 0绿, s = 1黄, s = 2红 
	memset(s, 0, sizeof(s));
	memset(r, 0, sizeof(r));
	for (int i = 1; i < n; i++)
		k = min(k, ti[i]);
	k -= 5; int t = k;
	for (int i = 0; i < n; i++) {
		r[i] = (ti[i] - 5) - k;
		if (r[i] == 0) {
			r[i] = 5;
			s[i] = 1;
  		}
  		else s[i] = 0;
	}
 	while (t <= 3600) {
 		k = r[0];
 		int sum = 0;
 		for (;sum < n; sum++)
 			if (s[sum]) break;
		if (sum == n) break;
 		for (int i = 1; i < n; i++)
 			k = min(k, r[i]);
		for (int i = 0; i < n; i++) {
			r[i] -= k;
			if (r[i]) continue;
			if (s[i] == 0) {
				s[i] = 1;
				r[i] = 5;
   			}
   			else if (s[i] == 1) {
   				s[i] = 2;
   				r[i] = ti[i];
      		}
      		else {
      			s[i] = 0;
      			r[i] = ti[i] - 5;
   			}
  		}
  		t += k;
  	}
  	if (t > 3600) printf("Set %d is unable to synch after one hour.\n", ++cas);
  	else {
  		int minu = t / 60;
  		int sec = t % 60;
  		printf("Set %d synchs again at %d minute(s) and %d second(s) after all turning green.\n", ++cas, minu, sec);
   	}
}

int main() {
	while (gets(str) != NULL) {
		int len = strlen(str); n = 0; str[len++] = ' ';
		int num = 0;
  		for (int i = 0; i < len; i++) {
  			if (str[i] >= '0' && str[i] <= '9') {
  				num = num * 10 + str[i] - '0';
  				continue;
        	}
        	ti[n++] = num;
        	num = 0;
  		}
  		solve();
 	}
	return 0;
}