HDU 5938 Four Operations(枚举)

http://acm.hdu.edu.cn/showproblem.php?pid=5938

题意,给出一串数字,在这串数字中按顺序插入+ - * /,问能得到最大的数字是多少。比如样例,1+2-3*4/5=1.

解法:很明显大小为20的字符串,肯定要开long long。如果直接枚举四个位置复杂度就是20^4,会TLE。所以我把它拆开出来,我枚举+和-的位置,记录下若该位置为-时候能得到最大的数字。然后枚举- * /的位置,记录下该位置若为- * /时候可以得到的最小值。最后for一遍减号能取到的位置,看看哪个位置Max - Min最大,记录下来,即为答案。复杂度降为n^3。

代码如下:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll sum, a[100005], ans;
int main() {
	ll T, n, k, Case = 1;	
	cin >> T;
	while(T--) {
		sum = 0;
		scanf("%I64d%I64d", &n, &k);
		for(int i = 0; i < n; i++) {
			scanf("%I64d", &a[i]);
			sum += a[i];
		}
		if(sum % k == 0) {
			ll ave = sum / k;
			ans = 0;
			for(int i = 0; i < n; i++) {
				if(a[i] < ave) {
					for(int j = i + 1; j < n; j++) {
						a[i] += a[j];
						ans += 1;
						if(a[i] == ave) {
							i = j;
							break;
						}
						else if(a[i] > ave) {
							ans += a[i] / ave;
							a[j] = a[i] - a[i] / ave * ave;
							if(a[j]) {
								i = j - 1;
							} else {
								i = j;
								ans--;
							}
							break;
						}
					}
				} else if(a[i] > ave) {
					ans += a[i] / ave;
					a[i] = a[i] - a[i] / ave * ave;
					if(a[i])
						i = i - 1;
					else
						ans--;
				}
			}
			printf("Case #%I64d: %I64d\n", Case++, ans);
		} else {
			printf("Case #%I64d: -1\n", Case++);
		}
	}
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值