这题是一个非常常用的模板。
同时进食后人
题目描述
已知会读入一个,接下来1行,读入个整数 (注意:是整数,不是正整数) ,要我们输出最终这个数的和。
思路分析
这题由于的范围最大为, 而C++一秒内跑的操作次数明显很悬,很容易。而我当时大意了,自信满满的脚上自己的答案,结果……(), 不得不说,这题很大的挫折了我的自信心
如果按正常做法只能拿, 然后会喜提,
#include <bits/stdc++.h>
using namespace std;
int n;
long long sum;
inline int read() {
int s = 0, w = 1;
char ch = getchar();
while (ch < '0' || ch > '9') {
if (ch == '-')
w = -1;
ch = getchar();
}
while (ch >= '0' && ch <= '9') {
s = (s << 1) + (s << 3) + (ch ^ 48);
ch = getchar();
}
return s * w;
}
int main() {
n = read();
for (; n--; ) {
int x = read();
sum += x + 0LL;
}
printf("%lld\n", sum);
return 0;
}回归正题,我们需要在进行一些优化。而明显,读入整数这一部分无法再进行优化。所以我们转而去考虑读入字符这一部分。
, 答案揭晓:
我们可以用指针与进行二次优化
char *p1,*p2,buf[100000];
#define nc() (p1==p2 && (p2=(p1=buf)+fread(buf,1,100000,stdin),p1==p2)?EOF:*p1++)这样,此题就能过了。
完整代码如下:
#include <bits/stdc++.h>
using namespace std;
char *p1,*p2,buf[100000];
#define nc() (p1==p2 && (p2=(p1=buf)+fread(buf,1,100000,stdin),p1==p2)?EOF:*p1++)
int read()
{
int x=0,f=1;
char ch=nc();
while(ch<48||ch>58)
{
if(ch=='-')
f=-1;
ch=nc();
}
while(ch>=48&&ch<=57)
x=x*10+ch-48,ch=nc();
return x*f;
}
int n,ans;
int main() {
cin>>n;
int x;
for(int i=1;i<=n;i++){
x=read();
ans+=x;
}
cout<<ans;
return 0;
你绝对不可以COPY哦!!!
}