小明种苹果(201909-1CCF)———附带思路和完整代码

    科技2025-07-21  6

    文章目录

    0 效果1 题目2 思路3 代码

    0 效果

    1 题目

    2 思路

    1 首先设置T(初值为0,方便累加)、P(初值为INT_MAX,方便比较)、k(初值为0或者其他)三个变量为最终需要的结果,cnt为苹果树的编号(初值为0);2 对于每行 进行输入的开始时,对cnt++;输入的苹果个数和掉的数量,使用tempP进行+=运算,运算的结果tempP再与T进行+=运算;运算结果tempP与P进行比较,如果比P小,则k = cnt, P = tempP; 3 最后输出T、k、P。

    注⚠️:

    这样操作,每次都只保存当行的结果,不用进行sort排序,既节省空间,又节省时间。为了防止输出int溢出(1000个106,而int最大值也才2*109)

    3 代码

    #include<cstdio> #include<limits.h> #include<math.h> #include<stdlib.h> int main(){ int n, m; scanf("%d%d", &n, &m); long long T = 0, P = INT_MAX;//输出值 int k = 0; int cnt = 0;//行数 while(n--){ cnt++; int t, num; long long tempP = 0; scanf("%d", &t); T += t; for(int i = 0; i < m;i++){ scanf("%d", &num); tempP += num; } T += tempP; if(tempP < P){ P = tempP; k = cnt; } } printf("%d %d %d", T, k, llabs(P)); return 0; }
    Processed: 0.016, SQL: 8