Tuesday, October 15, 2019

UVa 787 - Maximum Sub-sequence Product

// UVa 787 - Maximum Sub-sequence Product

import java.math.BigInteger;
import java.util.Scanner;

public class Main {

    private static BigInteger maxProduct;
    private static final BigInteger NEGATIVE_INFINITY = BigInteger.valueOf(1000000).pow(100).multiply(BigInteger.valueOf(-1));

    private static void consider(BigInteger product) {
        if (product.compareTo(maxProduct) > 0)
            maxProduct = product;
    }

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        while (scanner.hasNextInt()) {

            maxProduct = NEGATIVE_INFINITY;
            BigInteger productFromStart = BigInteger.ONE;
            BigInteger productAfterFirstNeg = NEGATIVE_INFINITY; // productAfterFirstNeg will be -oo if there are no negatives so far
            for (int i = scanner.nextInt(); i != -999999; i = scanner.nextInt()) {
                if (i == 0) {
                    consider(BigInteger.ZERO);
                    productFromStart = BigInteger.ONE;
                    productAfterFirstNeg = NEGATIVE_INFINITY;
                } else if (i > 0) {
                    productFromStart = productFromStart.multiply(BigInteger.valueOf(i));
                    consider(productFromStart);
                    if (productAfterFirstNeg.compareTo(NEGATIVE_INFINITY) != 0) {
                        productAfterFirstNeg = productAfterFirstNeg.multiply(BigInteger.valueOf(i));
                        consider(productAfterFirstNeg);
                    }
                } else {
                    productFromStart = productFromStart.multiply(BigInteger.valueOf(i));
                    consider(productFromStart);
                    if (productAfterFirstNeg.compareTo(NEGATIVE_INFINITY) != 0) {
                        consider(productAfterFirstNeg);
                        productAfterFirstNeg = productAfterFirstNeg.multiply(BigInteger.valueOf(i));
                        consider(productAfterFirstNeg);
                    } else {
                        productAfterFirstNeg = BigInteger.ONE;
                    }
                }
            }

            System.out.println(maxProduct);
        }
    }
}

Tuesday, October 8, 2019

UVa 10901 - Ferry Loading III

# UVa 10901 - Ferry Loading III

from collections import deque

def other(bank_name):
    if bank_name == 'left':
        return 'right'
    else:
        return 'left'

class Car:
    def __init__(self, arrival_time, arrival_bank):
        self.arrival_time = arrival_time
        self.arrival_bank = arrival_bank
        self.unload_time = 0
    def unload(self, time):
        self.unload_time = time

class Ferry:
    def __init__(self, ferry_capacity, crossing_time):
        self.ferry_capacity = ferry_capacity
        self.crossing_time = crossing_time
        self.bank = 'left'
        self.current_time = 0
        self.car_marker = 0
        self.cars_loaded = []
    
    def load(self, car):
        self.cars_loaded.append(car)
        
    def load_bank(self):
        while bank[self.bank] and len(self.cars_loaded) < self.ferry_capacity and bank[self.bank][0].arrival_time <= self.current_time:
            self.load(bank[self.bank].popleft())

    def switch_bank(self):
        self.bank = other(self.bank)
        self.current_time = self.current_time + self.crossing_time
        if self.cars_loaded:
            for loaded_car in self.cars_loaded:
                loaded_car.unload(self.current_time)
        self.cars_loaded = []

    def wait_for_next_car(self):
        if not bank['left'] and not bank['right']:
            return
        if not bank['right'] or (bank['left'] and bank['left'][0].arrival_time < bank['right'][0].arrival_time):
            next_car = bank['left'][0]
        else:
            next_car = bank['right'][0]
        self.current_time = next_car.arrival_time

    def run(self):
        self.current_time = 0        
        
        while bank['left'] or bank['right']:

            self.load_bank()
            if self.cars_loaded:
                self.switch_bank()
                continue
            
            if bank[other(self.bank)] and bank[other(self.bank)][0].arrival_time <= self.current_time:
                self.switch_bank()
                continue

            self.wait_for_next_car()

number_of_test_cases = int(input())
for test_case in range(1, number_of_test_cases+1):

    ferry_capacity, crossing_time, number_of_cars = map(int, input().split())
    
    cars = []
    bank = {'left': deque(), 'right': deque()}
    for i in range(number_of_cars):
        line = input().split()
        car_arrival_time = int(line[0])
        car_arrival_bank = line[1]
        car = Car(car_arrival_time, car_arrival_bank)
        bank[car.arrival_bank].append(car)
        cars.append(car)
                
    ferry = Ferry(ferry_capacity, crossing_time)
    ferry.run()

    for car in cars:
        print(f'{car.unload_time}')

Tuesday, October 1, 2019

UVa 11034 - Ferry Loading IV

# UVa 11034 - Ferry Loading IV

number_of_test_cases = int(input())
for test_case in range(1, number_of_test_cases+1):

    ferry_length, number_of_cars = map(int, input().split())
    ferry_length = ferry_length * 100

    available_space = {'left': ferry_length, 'right':ferry_length}
    number_of_trips_to_serve = {'left': 0, 'right': 0}

    for i in range(number_of_cars):
        car = input().split()
        car_length = int(car[0])
        bank = car[1]

        if available_space[bank] >= car_length:
            available_space[bank] = available_space[bank] - car_length
        else:
            number_of_trips_to_serve[bank] = number_of_trips_to_serve[bank] + 1
            available_space[bank] = ferry_length - car_length

    for bank in ['left', 'right']:
        if available_space[bank] < ferry_length:
            number_of_trips_to_serve[bank] = number_of_trips_to_serve[bank] + 1

    number_of_trips_required = max( number_of_trips_to_serve['left']*2-1  , number_of_trips_to_serve['right']*2 )

    print(f'{number_of_trips_required}' ) 

Tuesday, September 24, 2019

UVa 540 - Team Queue

// UVa 540 - Team Queue

import java.util.*;

public class Main {

    private static class TeamQueue<E, T> {

        private Map<E, T> memberToTeam = new HashMap<>();
        private Map<T, Queue<E>> teamToQueue = new HashMap<>();
        private Queue<T> teamOrder = new LinkedList<>();

        void addMember(E member, T teamIndex) {
            memberToTeam.put(member, teamIndex);
        }

        void enqueue(E member) {
            if (!memberToTeam.containsKey(member)) throw new IllegalArgumentException();
            T team = memberToTeam.get(member);

            if (!teamToQueue.containsKey(team)) {
                teamToQueue.put(team, new LinkedList<>());
            }
            if (teamToQueue.get(team).isEmpty()) {
                teamOrder.add(team);
            }
            teamToQueue.get(team).add(member);
        }

        E dequeue() {
            E member = teamToQueue.get(teamOrder.peek()).poll();
            while (!teamOrder.isEmpty() && teamToQueue.get(teamOrder.peek()).isEmpty())
                teamOrder.poll();
            return member;
        }

    }

    public static void main(String[] args) {
        int scenario = 0;
        try (Scanner scanner = new Scanner(System.in)) {

            while (true) {

                int numberOfTeams = scanner.nextInt();
                if (numberOfTeams == 0)
                    break;
                scenario++;
                System.out.println("Scenario #" + scenario);

                TeamQueue<Integer, Integer> teamQueue = new TeamQueue<>();

                for (int teamIndex = 0; teamIndex < numberOfTeams; teamIndex++) {
                    int teamSize = scanner.nextInt();
                    for (int j = 0; j < teamSize; j++) {
                        int member = scanner.nextInt();
                        teamQueue.addMember(member, teamIndex);
                    }
                }

                String instruction = scanner.next();
                while (!"STOP".equals(instruction)) {

                    if ("ENQUEUE".equals(instruction)) {
                        int member = scanner.nextInt();
                        teamQueue.enqueue(member);
                    } else {
                        System.out.println(teamQueue.dequeue());
                    }

                    instruction = scanner.next();
                }
                System.out.println();
            }
        }
    }
}

Tuesday, September 17, 2019

UVa 10114 - Loansome Car Buyer

// UVa 10114 - Loansome Car Buyer

program UVa10114;

type
    DeprecationRecord = record
        month : integer;
        percentage : real;
    end;

var
    durationInMonths : integer;
    downPayment, loanAmount : real;
    numberOfDepreciationRecords : integer;
    depreciation : array[1..102] of DeprecationRecord;
    sol, i : integer;

function completeMonthsBeforeBorrowerOwnsLessThanCarIsWorth : integer;
var
    monthsPassed : integer;
    carWorth : real;
    borrowerOwns : real;
    monthlyPayment : real;
begin
    carWorth := downPayment + loanAmount;
    borrowerOwns := loanAmount;
    monthlyPayment := loanAmount / durationInMonths;
    
    carWorth := carWorth - carWorth * depreciation[1].percentage;
    monthsPassed := 0;
    
    for i:= 2 to numberOfDepreciationRecords do begin
        if (borrowerOwns < carWorth) then break;
        while (monthsPassed + 1 < depreciation[i].month) do begin
            borrowerOwns := borrowerOwns - monthlyPayment;
            carWorth := carWorth - (carWorth * depreciation[i-1].percentage);
            monthsPassed := monthsPassed + 1;
            if (borrowerOwns < carWorth) then break;
        end;
        if (borrowerOwns < carWorth) then break;
    end;
    completeMonthsBeforeBorrowerOwnsLessThanCarIsWorth := monthsPassed;
end;

begin
    while not EOF() do begin
        readln(durationInMonths, downPayment, loanAmount, numberOfDepreciationRecords);
        if (durationInMonths < 0) then break;
        for i:= 1 to numberOfDepreciationRecords do begin
            readln(depreciation[i].month, depreciation[i].percentage);
        end;
        numberOfDepreciationRecords := numberOfDepreciationRecords + 1;
        depreciation[numberOfDepreciationRecords].month := durationInMonths + 1;
        depreciation[numberOfDepreciationRecords].percentage := 0;
        sol := completeMonthsBeforeBorrowerOwnsLessThanCarIsWorth;
        write(sol,' ');
        if sol = 1 then writeln('month') else writeln('months');
    end;
end.

Tuesday, September 10, 2019

UVa 12157 - Tariff Plan

# UVa 12157 - Tariff Plan

from functools import reduce
def sum(x1, x2): return x1 + x2

number_of_test_cases = int(input())
for test_case in range(1, number_of_test_cases+1):
  
  number_of_calls = int(input())
  call_durations = list(map(int, input().split()))
  
  cost_for_Miles_plan = reduce(sum, map(lambda x: x//30+1, call_durations)) * 10
  cost_for_Juice_plan = reduce(sum, map(lambda x: x//60+1, call_durations)) * 15

  cheapest_cost = min(cost_for_Miles_plan, cost_for_Juice_plan)
  if cost_for_Miles_plan < cost_for_Juice_plan:
    cheapest_plan = 'Mile'
  elif cost_for_Miles_plan > cost_for_Juice_plan:
    cheapest_plan = 'Juice'
  else:
    cheapest_plan = 'Mile Juice'

  print(f'Case {test_case}: {cheapest_plan} {cheapest_cost}' ) 

Tuesday, September 3, 2019

UVa 12798 - Handball

# UVa 12798 - Handball

while True:
    try:
        numberOfPlayers, numberOfGames = map(int, input().split())
    except:
        break
    
    playersThatScoredInAllGames = 0
    for player in range(numberOfPlayers):
        playerScoresByGame = map(int, input().split())
        scoredInAllGames = not (0 in playerScoresByGame)
        if scoredInAllGames: playersThatScoredInAllGames += 1

    print(playersThatScoredInAllGames)