您的位置:首页 > 编程语言 > Go语言

uva11054 - Wine trading in Gergovia(葡萄酒交易)

2013-04-07 16:40 363 查看
对于这个题,思路不难,但是我犯了几个致命的小错。

当a[i]<0时,忘了对a[i]的符号进行处理。用tt对符号处理后又忘了对tt进行实时更新。

思路:从一端到另一端,进行遍历,如果该项小于0,则从最近的后方大于0的位置处拿数,如果不够则再从下一个大于0的位置处拿数,

如果该项大于0,因其前面的都已满足,所以应该把该项的值往后搬。由于所有的项之和等于0,所以这样向后搬下去,一定存在某个位置用得上这些移动的值。

先给出几组测试数组:

input:

10
-2100 500 400 300 200 500 800 400 600 -1600
15
-1 -2 -3 -4 5 -6 7 -8 9 -10 11 -12 13 -14 15
0

output:

9900
100


个人代码:

#include <cstdio>
#define M 100010
int n, a[M];
int main ()
{
long long ans;
while(scanf("%d",&n),n)
{
ans = 0;
for(int i = 0; i < n; i++) scanf("%d",&a[i]);
for(int i = 0; i < n; i++)
{
if(a[i]==0) continue;
if(a[i]<0) for(int j = i+1, tt; j < n&&a[i]<0; j++)
{
if(a[j]<=0) continue;
tt = -1*a[i];
if(a[j]>=tt) { ans += (j-i)*tt; a[j]-=tt; a[i] = 0; }
else { ans+=(j-i)*a[j]; a[i] += a[j]; a[j] = 0; }
}
else
{
ans+=a[i];
a[i+1]+=a[i];
a[i] = 0;
}
}
printf("%lld\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: