JZOJ 5820. 【NOIP提高A组模拟2018.8.16】 非法输入
Description
在算法競(jìng)賽中,題目一般保證了輸入數(shù)據(jù)的合法性。然而在工程開發(fā)中,我們往往不期望程 序得到的輸入都是合法的。
D 君正忙著向校內(nèi) OJ 添加題目,在寫了第 233 個(gè) val.cpp 之后,她的頭腦中涌現(xiàn)出了這樣 的想法。于是她決定出一道不需要寫 val.cpp 的題。
輸入兩個(gè)整數(shù),你需要做的就是輸出她們的和。
Input
第一行一個(gè)正整數(shù) T。
接下來 T 行,每行代表一組數(shù)據(jù)。
一組合法的數(shù)據(jù)包含由一個(gè)空格隔開的兩個(gè)合法的十進(jìn)制整數(shù),行首和行尾不包含任何多余 的字符。
一個(gè)合法的十進(jìn)制整數(shù)要么是 0,要么由一個(gè)可選的負(fù)號(hào),一個(gè) 1 到 9 之間的數(shù)字,和若干 個(gè) 0 到 9 之間的數(shù)字順序連接而成,并且這兩個(gè)數(shù)字均在區(qū)間 [?2^31 , 2^31) 之內(nèi)。
一組不合法的數(shù)據(jù)是一個(gè)不匹配以上規(guī)則的字符串。
Output
對(duì)于每組數(shù)據(jù),如果該數(shù)據(jù)是合法的請(qǐng)輸出一行一個(gè)整數(shù)代表答案,否則請(qǐng)輸出 Input Error。
Sample Input
6
1 1
-1 -1
1 1
asdf
2147483648 0
Sample Output
2
-2
Input Error
Input Error
Input Error
Input Error
Data Constraint
Solution
純模擬題。。
但是有很多細(xì)節(jié),比賽時(shí)AC的人不多。。
我就少考慮了兩個(gè)地方:讀入三個(gè)數(shù),符號(hào)后面沒有數(shù)字。
Code
#include<cstdio> #include<cstring> #include<iostream> #include<cctype> using namespace std; typedef long long LL; const int N=5e4; int T; LL up,low; char s[N]; int main() {freopen("aplusb.in","r",stdin);freopen("aplusb.out","w",stdout);scanf("%d\n",&T);up=1LL<<31,low=-up;while(T--){cin.getline(s,N);int n=strlen(s);if(!isdigit(s[0]) && s[0]!='-'){puts("Input Error");continue;}if(!isdigit(s[n-1])){puts("Input Error");continue;}int f1=0,f2=0;if(s[0]=='-') f1=1;int l1=0,l2=0;for(int i=f1;i<n;i++)if(isdigit(s[i])) l1++; else break;if(l1>10 || s[f1+l1]!=' ' || !l1){puts("Input Error");continue;}if(!isdigit(s[f1+l1+1]) && s[f1+l1+1]!='-'){puts("Input Error");continue;}if(s[f1+l1+1]=='-') f2=1;int pos=-1;for(int i=f1+l1+1+f2;i<n;i++)if(isdigit(s[i])) l2++; else{pos=i;break;}if(l2>10 || pos>=0 && pos<n-1 || !l2){puts("Input Error");continue;}if(l1==1 && s[f1]=='0' && f1){puts("Input Error");continue;}if(s[f1]=='0' && l1>1){puts("Input Error");continue;}if(l2==1 && s[f1+l1+1+f2]=='0' && f2){puts("Input Error");continue;}if(s[f1+l1+1+f2]=='0' && l2>1){puts("Input Error");continue;}LL x=0,y=0;for(int i=f1;i<f1+l1;i++) x=x*10+s[i]-'0';for(int i=f1+l1+1+f2;i<n;i++) y=y*10+s[i]-'0';if(f1) x=-x;if(f2) y=-y;if(x<low || x>=up){puts("Input Error");continue;}if(y<low || y>=up){puts("Input Error");continue;}printf("%lld\n",x+y);}return 0; }總結(jié)
以上是生活随笔為你收集整理的JZOJ 5820. 【NOIP提高A组模拟2018.8.16】 非法输入的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JZOJ 5794. 2018.08.1
- 下一篇: JZOJ 5850. 【NOIP提高组模