PAT B1010 十行代码方案
题目在这里:(https://pintia.cn/problem-sets/994805260223102976/problems/994805313708867584)
今天看到《算法笔记》里面的pat b1010的参考代码,有种小题大做的感觉,参考代码如下:
#include <cstdio>
int main(){
int a[1010]={0};
int k,e,count=0;
while (scanf("%d%d",&k,&e)!=EOF){
a[e]=k;
}
for (int i=0; i<=1000; i++){
a[i-1]=a[i]*i;
a[i]=0;
if(a[i-1]) count++;
}
if (!count) printf("0 0");
else {
for (int i=1000; i>=0; i--){
if (a[i]!=0){
printf("%d %d",a[i],i);
count--;
if (count!=0) printf(" ");
}
}
}
}
思路挺好的,但是代码太长了,不够直观,这个问题最终感觉核心是系数的问题,捣鼓了半天,发现了一个十行就能解决的代码,其实是11行,如下:
#include <cstdio>
int main(){
int a,b,count=0;
while (scanf("%d%d",&a,&b)==2){//或者 while (scanf("%d%d",&a,&b)!=EOF)也行
if (a*b){ //a*b也就是系数,等于0就直接跳过
if (count++) printf(" ");//第一次不加空格,其余都加一个空格
printf("%d %d",a*b,b-1);
}
}
if (!count) printf("0 0"); //有可能系数全为零
}
while 循环条件读取数据之所以用scanf("%d%d",&a,&b)==2,是为了方便自己用dev C++测试,用EOF来判断更常规,两种方案都可以,这个代码就直观简单很多,但是短时间内不一定能想到。还是算法笔记里面的想法比较朴实一点。