程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> UVA 467 - Synching Signals(數論)

UVA 467 - Synching Signals(數論)

編輯:C++入門知識

UVA 467 - Synching Signals

題目鏈接

題意:給定幾個紅綠燈,每個紅綠燈time表示,time秒紅燈,time - 5秒綠燈, 5秒黃燈.
然後求全部燈變綠之後,在一次有燈變換之後,全是綠燈需要的時間

思路:由於只要算1小時,也就是3600秒,直接暴力過去,每次時間加上當前最小能變換燈的時間,然後記錄一下每個燈的顏色狀態,直到全變綠為止

代碼:

#include 
#include 
#include 
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;
}


  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved