Page Count (字符串+模拟)

来源:互联网 发布:windows使窗口变灰api 编辑:程序博客网 时间:2024/06/06 02:20

When you execute a word processor'sprint command, you are normally prompted to specify the pages you want printed. You might, for example, enter:

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

The expression you enter is a list of print ranges, separated by commas.

Each print range is either a single positive integer, or two positive integers separated by a hyphen. In the latter case we call the first integerlow and the second onehigh. A print range for whichlow > high is simply ignored. A print range that specifies page numbers exceeding the number of pages is processed so that only the pages available in the document are printed. Pages are numbered starting from 1.

Some of the print ranges may overlap. Pages which are common to two or more print ranges will be printed only once. (In the example given, pages 13, 14 and 15 are common to two print ranges.)

input

The input will contain data for a number of problem instances. For each problem instance there will be two lines of input. The first line will contain a single positive integer: the number of pages in the document. The second line will contain a list of print ranges, as defined by the rules stated above. End of input will be indicated by 0 for the number of pages. The number of pages in any book is at most 1000. The list of print ranges will be not be longer than 1000 characters.

output

For each problem instance, the output will be a single number, displayed at the beginning of a new line. It will be the number of pages printed by theprint command.

sample 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

sample output17
12

题意:给你一个数字是一本书的页数,然后一行字符串代表印刷页数,但是有些指令是不合法的,可以直接删除。

分析:多组数据以0结束。使用了一个数组来标记是否被印刷,1为已印刷,0为未被印刷,最后统计1的个数即可。for循环那边卡了很久,还有就是注意数组的归零。

#include<cstdio>#include<cmath>#include<iostream>#include<string>#include<cstring>using namespace std;int a[1005];void judge(int begin,int end){if(begin<=end){for(int i=begin;i<=end;i++){a[i]=1;}}}int main(){int len,t,cnt;char str[1005];while(scanf("%d",&t),t){cnt=0;memset(a,0,sizeof(a));scanf("%s",str);len=strlen(str);for(int i=0;i<len;){   int j=i,suma=0,sumb=0;           for(;str[j]!='-'&&str[j]!=','&&j<len;j++)           suma=suma*10+str[j]-'0';   if(str[j]=='-')   {   int k=j+1;           for(;str[k]!='-'&&str[k]!=','&&k<len;k++)           sumb=sumb*10+str[k]-'0';judge(suma,sumb);i=k+1;      }else{a[suma]=1;i=j+1;}   }for(int i=1;i<=t;i++){if(a[i]==1)cnt++;}printf("%d\n",cnt);}} 

原创粉丝点击