E-Cardboard for Pictures

本文描述了一位程序员在Codeforces平台上遇到的编程问题,他们最初尝试使用求根公式解决数学问题,但未能通过样例测试。后来,他们发现正确方法是应用二分查找算法。然而,在实现过程中遇到了整数溢出的运行时错误。作者分享了修正后的代码,并提到了Codeforces提供的错误诊断帮助。
摘要由CSDN通过智能技术生成

Problem - E - Codeforces

一开始想用求根公式,然后样例都过不了,谢谢样例。代码被我弄丢了,下次一定及时存代码。

结果正解是二分啊。

#include<bits/stdc++.h>
#define int long long
#define pii pair<int,int>
using namespace std;



void solve()
{
    int n;
    int c;
    cin>>n>>c;
    int a=0;int b=0;
    for(int i=1;i<=n;i++)
    {
        int s;
        cin>>s;
        a+=s*s;
        b+=s;
    }
    c-=a;c/=4;
    int l=1;//原来是0
    int r=1e9;
    int ans;
    //cout<<b<<" "<<c<<endl;
    while(l<=r)
    {
        int mid=(l+r)/2;
        int cc=b*mid+mid*mid*n;
        if(cc>c)
        {
            r=mid-1;
        }
        else if(cc<c)
        {
            l=mid+1;
        }
        else
        {
            ans=mid;
            break;
        }
       
    }
     cout<<ans<<endl;
}
signed main()
{
    int t;
    cin>>t;
    while(t--)
    {
        solve();
    }
    
    return 0;
}

可是,一次性算好居然也不行!!cf好贴心,还有错误信息……

Diagnostics

Diagnostics detected issues [cpp.clang++-diagnose]: p71.cpp:29:29: runtime error: signed integer overflow: 250000000000000000 * 94 cannot be represented in type 'long long'

以下是和tutorial思路一模一样的代码

#include<bits/stdc++.h>
#define int long long
#define pii pair<int,int>
using namespace std;
 
const int maxn=2e5+5;
int s[maxn];
 
void solve()
{
    int n;
    int c;
    cin>>n>>c;
    int a=0;int b=0;
    for(int i=1;i<=n;i++)
    {
        
        cin>>s[i];
    }
   
    int l=1;//原来是0
    int r=1e9;
    int ans;
    //cout<<b<<" "<<c<<endl;
    while(l<=r)
    {
        int mid=(l+r)/2;
        int cc=0;
        for(int i=1;i<=n;i++)
        {
            cc+=(s[i]+mid)*(s[i]+mid);
            if(cc>c)
            {
                break;
            }
        }
 
        if(cc>c)
        {
            r=mid-1;
        }
        else if(cc<c)
        {
            l=mid+1;
        }
        else
        {
            ans=mid;
            break;
        }
       
    }
     cout<<ans/2<<endl;
}
signed main()
{
    int t;
    cin>>t;
    while(t--)
    {
        solve();
    }
    
    return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值