HDU_5053_2014年鞍山网络赛

本文介绍了解决一个特定编程问题的两种方法:一种是通过遍历指定区间内的每个整数并累加其立方值;另一种则是利用数学公式直接计算区间的立方和,这种方法避免了循环操作,提高了计算效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我当时怎么不知道有这么水的题。。。

题意:给一个范围[a,b],求区间内整数的立方和。弱弱的再吐槽一下:当时怎么没发现敲打

#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;

#define ll __int64

int main()
{
    ll a, b;
    int t;
    scanf("%d", &t);
    int ans = 1;
    while(t--)
    {
        ll sum = 0, i;
        scanf("%I64d%I64d", &a, &b);
        for(i=a; i<=b; ++i)
            sum += i*i*i;

        printf("Case #%d: %I64d\n", ans++, sum);
    }

    return 0;
}


可能是数据太水,用数学公式计算和上面的效率是一样的:

#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;

#define ll __int64

ll get3(ll n)
{
    ll x = n*(n+1)/2;
    return x * x;
}

int main()
{
    ll a, b;
    int t;
    scanf("%d", &t);
    int ans = 1;
    while(t--)
    {
        ll sum = 0, i;
        scanf("%I64d%I64d", &a, &b);

        if(!a)  a = 1;
        printf("Case #%d: %I64d\n", ans++, get3(b)-get3(a-1));
    }

    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值