Counting Pages

Interview

Time limit1sMemory limit256 MB

Summary
Given a document's page count and a comma-separated list of page ranges, count the distinct pages that are actually printed, ignoring empty ranges and pages past the end.
Level

Easy3 of 10

Topics
Implementation, String, Simulation, Array
Solved
No attempts yet

Problem

In a word processor (such as Word, Hangul, or Notepad), when you print you can specify the page ranges to print by typing them directly. For example, you might type:

10-15,25-28,8-4,13-20,9,8-8

You list the ranges you want to print, separated by commas (,).

Each print range is either a single positive integer, or two positive integers separated by a hyphen (-). In a range made of two numbers, call the first number low and the second high. The rules are:

  • If low > high, that range is not printed.
  • If a range goes beyond the document's page count, only the pages that actually exist are printed. Page numbers start at 1.
  • Ranges may overlap. An overlapping page is printed only once, not multiple times. (In the example above, pages 13, 14, and 15 belong to two ranges at once.)

Given the print ranges, write a program that counts how many distinct pages are actually printed.

Input

The input consists of several test cases. For each test case, the first line contains the total number of pages in the document, and the second line contains the print ranges in the format described above. The last line of the input contains a single 0.

A document has at most 1000 pages, and the length of a print-range string does not exceed 1000 characters.

Output

For each test case, print the number of distinct pages that are actually printed, one per line.

Examples1

  1. Example 1

    Input
    30
    10-15,25-28,8-4,13-20,9,8-8
    19
    10-15,25-28,8-4,13-20,9,8-8
    0
    
    Expected output
    17
    12