Translate

Views

Tuesday, June 6, 2023

Solution UVA: 161 - Traffic Lights


  Last Submissions
  Problem  VerdictLangTimeBestRankSubmit Time
 | discuss161 - Traffic Lights AcceptedC++110.0200.00018301 mins ago


Problem:  Click 161 to read

Suggest:

At the time I wrote this solution, there was almost no solution on google search, only code!

- First we need to understand the problem: it asks us to find the time at which all the lights turn green for the 2nd time (from 0 will be the time when they all turn green for the 1st time)

- To solve the problem: simply re-simulate all the lights on the time axis from 0 -> 18000 (5 hours), if there exists a moment where all the lights turn green for the 2nd time then we stop and print the result 


#include<bits/stdc++.h>
using namespace std;

int row = 0, n, n_min=1000111000;
int color[101][19000];

void f(int seconds) {
    int hours = seconds / 3600;
    int minutes = (seconds % 3600) / 60;
    seconds = seconds % 60;

    cout << setfill('0');
    cout << setw(2) << hours << ":";
    cout << setw(2) << minutes << ":";
    cout << setw(2) << seconds << "\n";
}

int main(){
    ios::sync_with_stdio(false); cin.tie(nullptr);

    while(cin >> n){
       
        if (n==0 && row==0) break;
       
        if (n==0 && row > 0){
           
            bool overtime= true;
            for(int j=n_min*2; j<=18000; j++){
                bool green= true;
               
                for(int i=1; i<=row; i++)
                if (color[i][j] != 1){
                    green= false;
                    break;  
                }
               
                if (green){
                    f(j);
                    overtime=false;
                    break;
                }
            }
            if (overtime) cout<<"Signals fail to synchronise in 5 hours\n";
            row=0;
            n_min=100011100;
            continue;
        }
       
        row++;
        n_min= min(n_min, (n==0?100011100:n));
        int red= 0;
        do{
           
            int green= red + n - 5;    
            for(int i=red; i < green; i++)
                color[row][i]= 1;
               
            int yellow = green + 5;
            for(int i=green; i<yellow; i++)
                color[row][i]= 2;
           
            red = yellow + n;
            for(int i=yellow; i<red; i++)
                color[row][i]= 3;
               
        }while(red <= 18000);
                                       
       
    }
}

No comments: