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;
    }


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

  • 相关阅读:
    Palindrome Partitioning
    triangle
    Populating Next Right Pointers in Each Node(I and II)
    分苹果(网易)
    Flatten Binary Tree to Linked List
    Construct Binary Tree from Inorder and Postorder Traversal(根据中序遍历和后序遍历构建二叉树)
    iOS系统navigationBar背景色,文字颜色处理
    登录,注销
    ios 文字上下滚动效果Demo
    经常崩溃就是数组字典引起的
  • 原文地址:https://www.cnblogs.com/lcchuguo/p/4658193.html
Copyright © 2011-2022 走看看