zoukankan      html  css  js  c++  java
  • uva:10700

    题目: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.
    ", caculate_max(count), caculate_min(count));
    		
    	}
    	return 0;
    }


    版权声明:本文博客原创文章,博客,未经同意,不得转载。

  • 相关阅读:
    6.etc目录下重要文件和目录详解
    5.linux目录结构介绍
    4.CRT远程连接的使用
    3.了解linux系统以及搭建学习环境
    记录groupby的一次操作
    keras 文本序列的相关api
    networkX.core_number(graph)
    关于无向图的最大团的问题。
    数据分析,numpy pandas常用api记录
    conda install 失败 http404
  • 原文地址:https://www.cnblogs.com/lcchuguo/p/4658193.html
Copyright © 2011-2022 走看看