一开始想用求根公式,然后样例都过不了,谢谢样例。代码被我弄丢了,下次一定及时存代码。
结果正解是二分啊。
#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;
}