码迷,mamicode.com
首页 > 其他好文 > 详细

uva:10700 - Camel trading(贪心)

时间:2014-07-05 23:43:50      阅读:221      评论:0      收藏:0      [点我收藏+]

标签:http   os   for   代码   io   line   

题目:10700 - Camel trading


题目大意:给出一些表达式,表达式由数字和加号乘号组成,数字范围【1,20】。这些表达式可能缺少了括号,问这样的表达式加上括号后能得到的最大值和最小值。

解题思路:因为这些数的都是正整数,所以可以用贪心。不然看出最大值就是先做完加法在做乘法,最小值就是先做乘法在做加法。注意这里的数值要用long long 因为比表达式的值可能会超过int。

代码:

#include <stdio.h>
#include <string.h>

const int N = 15;
char op[N];
char str[3 * N];
long long num[N];

long long caculate_max (int count) {

	long long temp[N];
	for (int i = 0; i < count; i++)
		temp[i] = num[i];

	for (int i = count - 2; i >= 0; i--)
		if (op[i] == '+') {

			temp[i] += temp[i + 1];
			temp[i + 1] = temp[i];
		}

	long long sum = temp[0];
	for (int i = 0; i < count - 1; i++) {

		if (op[i] == '*') 
			sum *= temp[i + 1];

	}
	return sum;
}

long long caculate_min (int count) {

	long long temp[N];
	for (int i = 0; i < count; i++)
		temp[i] = num[i];

	for (int i = count - 2; i >= 0; i--) {

		if (op[i] == '*')
			temp[i] = temp[i] * temp[i + 1];
	}

	long long sum = temp[0];
	for (int i = 0; i <= count - 2; i++) {

		if (op[i] == '+')
			sum += temp[i + 1];
	}

	return sum;
}

int init () {

	int t = 0;
	long long sum;
	scanf ("%s", str);
	for (int i = 0; i < strlen (str); i++) {

		if (str[i] == '+' || str[i] == '*')
			op[t++] = str[i];
		else {

			sum = 0;
			while (str[i] >= '0' && str[i] <= '9') {

				sum = sum * 10 + str[i] - '0';
				i++;
			}
			num[t] = sum;
			i--;
		}
	}
	return t + 1;
}

int main () {

	int t;
	int count;
	scanf ("%d", &t);
	while (t--) {

		count = init();	
		printf ("The maximum and minimum are %lld and %lld.\n", caculate_max(count), caculate_min(count));
		
	}
	return 0;
}


uva:10700 - Camel trading(贪心),布布扣,bubuko.com

uva:10700 - Camel trading(贪心)

标签:http   os   for   代码   io   line   

原文地址:http://blog.csdn.net/u012997373/article/details/36757647

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!