传送门:Problem - 1186D - Codeforces
输入的数要么向上取整,要么向下取整,那么设ans为负数的绝对值的和,sum为正数的和,对单一的负数向下取整于负数而言相当于ans++,同理正数向上取整sum++。
这里我们设ans1为ans的最小值即负数全部向上取整,ans2为ans最大值,sum1,sum2同理
由于题目保证答案存在,故ans1必定小于sum2,我们只要通过改变取整方式,让它们“会合”即可使得新序列的和为0
我们遍历序列,遇见负数改变ans1的值,遇见正数改变sum2的值,ans1++即输出负数向下取整,sum2--即输出正数向下取整,一旦ans1==ans2时负数变为向上取整,ans1停止变化,sum1==sum2时正数变为向上取整,ans1==sum2时同理。
此时输出的序列符合条件
#include<iostream> #include<cstdio> #include<cstring> #include<cmath> #include<queue> #include<algorithm> #define ll long long using namespace std; ll n,m; double a[500010]; ll sum1,sum2; ll ans1,ans2; int main(){ cin>>n; for(ll i=1;i<=n;i++) { ll flag=0; double x; cin>>x; a[i]=x; if(x<0)flag=1; x=fabs(x); ll y; y=x*1; if(x==y) { if(flag){ ans1+=y; ans2+=y; } else{ sum1+=y; sum2+=y; } } else{ if(flag) { ans1+=y; ans2+=(y+1); } else{ sum1+=y; sum2+=(y+1); } } } //cout<<ans2<<" "<<sum1<<endl; for(ll i=1;i<=n;i++) { if(ans2!=sum1) { ll y=a[i]*1; if(y==a[i]) { cout<<y<<endl; continue; } if(a[i]<0) { //ll y=a[i]*1; cout<<y<<endl; ans2--; } else{ //ll y=a[i]*1; cout<<y+1<<endl; sum1++; } } else { ll y=a[i]*1; if(y==a[i]) { cout<<y<<endl; continue; } if(a[i]<0) { //ll y=a[i]*1; cout<<y-1<<endl; } else{ //ll y=a[i]*1; cout<<y<<endl; } } } return 0; }