1. 程式人生 > >算法訓練 C*++ Calculations

算法訓練 C*++ Calculations

初始 value rcp 大致 gpo 語言 def 另有 tput

算法訓練 C*++ Calculations 時間限制:2.0s 內存限制:64.0MB 問題描述   C*++語言和C++語言非常相似,然而C*++的程序有時會出現意想不到的結果。比如像這樣的算術表達式:
  表達式=基本式 / 表達式+基本式 / 表達式-基本式
  基本式=增量 / 系數*增量
  增量=a++ / ++a
  系數=0/1/2/……/1000
  如“5*a++-3*++a+a++”是合法的C*++表達式。
  計算這樣的表達式的值的方法:首先是每個基本式進行計算,然後按照正常的算術運算法則計算。如果一個基本式包含“a++”,則先進行乘法運算再使變量a權值+1;如果一個基本式包含“++a”,則先使變量a權值+1再進行乘法運算。
  然而基本式可以按任意順序計算,這就是為什麽計算結果是完全無法預料的。
  你的任務就是去找到最大的可能結果。

  第一行,一個整數n,表示變量a的初始值。
  第二行,一個合法的C*++表達式。

  共一行,一個整數ans,表示最大可能結果。 輸入格式   input 1:
  1
  5*a++-3*++a+a++
  input 2:
  3
  a+++++a 輸出格式   output 1:
  11
  output 2:
  8 數據規模和約定   對於20%的數據,表達式長度<=20。
  另有20%的數據,滿足n>=0。
  對於100%的數據,-1000<=n<=1000,表達式長度<=10000。
  註意表達式開頭可能有負號!
 1
#include <stdio.h> 2 #include <string.h> 3 #define MAXSIZE 10011 4 /*大致思想為將每個++a或者a++的系數提取出來進行排序,之後按照 5 a從初始值開始遞增的形式進行相加,需要註意的是++a的情況,需要提前額外加一次*/ 6 int n, ans, k, coe, len, outcome, c[MAXSIZE]; 7 char e[MAXSIZE], s[MAXSIZE]; 8 9 void sort(int x) 10 { 11 int i, j, t; 12 13 for
(i = 1; i < x; i ++){ 14 for(j = i+1; j > 1; j--){ 15 16 if(c[j] < c[j-1]){ 17 t = c[j-1]; 18 c[j-1] = c[j]; 19 c[j] = t; 20 }else{ 21 break; 22 } 23 } 24 } 25 } 26 27 int
calculate() 28 { 29 int i, j; 30 31 k = outcome = 0; 32 strcpy(s, e); 33 len = strlen(s); 34 35 if(s[0] != -){ 36 37 for(i = len + 1; i > 0; i --){ 38 s[i] = s[i-1]; 39 } 40 41 s[0] = +; 42 len ++; 43 } 44 45 for(i = 0; i < len; i += 3){ 46 47 if(s[i] == +){ 48 coe = 1; 49 }else{ 50 coe = -1; 51 } 52 53 i ++; 54 j = 0; 55 while(0 <= s[i] && s[i] <= 9){ 56 j *= 10; 57 j += s[i++] - 0; 58 } 59 60 if(s[i] == *){ 61 i ++; 62 }else{ 63 j = 1; 64 } 65 66 coe *= j; 67 c[++k] = coe; 68 outcome += (n-(s[i] == a)) * coe; 69 } 70 71 sort(k); 72 for(i = 1; i <= k; i ++){ 73 outcome += i * c[i]; 74 } 75 76 return outcome; 77 } 78 79 int main() 80 { 81 scanf("%d %s", &n, e); 82 83 ans = calculate(); 84 85 printf("%d\n", ans); 86 87 return 0; 88 }

算法訓練 C*++ Calculations