Long Distance Racing

Interview

Time limit1sMemory limit128 MB

Summary
Given a terrain string and per-unit times, find the farthest segment index k whose round-trip time stays within M seconds.
Level

Medium4 of 10

Topics
Array, Prefix sum, Implementation, Binary search
Solved
No attempts yet

Problem

Bessie is training for her next race by running on a path that includes hills, so she will be ready for any terrain. She has chosen a single straight path and wants to run as far from the farm as she can, but she must be back at the farm within MM seconds (1≤M≤10,000,0001 \le M \le 10{,}000{,}000).

The chosen path is TT units long (1≤T≤100,0001 \le T \le 100{,}000) and is split into equal-length segments, each of which is uphill, flat, or downhill. Segment ii is given by a single character SiS_i, where u means uphill, f means flat, and d means downhill.

Bessie takes UU seconds to run one unit of uphill (1≤U≤1001 \le U \le 100), FF seconds for one unit of flat (1≤F≤1001 \le F \le 100), and DD seconds for one unit of downhill (1≤D≤1001 \le D \le 100). On the way home, every uphill segment becomes downhill and every downhill segment becomes uphill (flat stays flat).

If Bessie runs to the end of segment kk and returns, she passes segments 11 through kk in order on the way out and the same segments in reverse on the way back. Find the greatest distance (number of units) she can reach from the farm and still return within MM seconds.

Input

  • Line 1: Five space-separated integers MM, TT, UU, FF, and DD.
  • Lines 2 through T+1T+1: line i+1i+1 contains a single character SiS_i describing segment ii.

Output

  • A single integer: the greatest distance (number of units) Bessie can reach from the farm and still return within MM seconds.

Examples2

  1. Example 1

    Input
    13 5 3 2 1
    u
    f
    u
    d
    f
    
    Expected output
    3
    
  2. Example 2

    Input
    1 3 5 5 5
    u
    f
    d
    
    Expected output
    0