首页 > ACM题库 > HDU-杭电 > Hdu 1901 Smeech-模拟[解题报告] C++
2013
12-23

Hdu 1901 Smeech-模拟[解题报告] C++

Smeech

问题描述 :

Professor Octastichs has invented a new programming language, Smeech. An expression in Smeech may be a positive or negative integer, or may be of the form (p e1 e2) where p is a real number between 0 and 1 (inclusive) and e1 and e2 are Smeech expressions. The value represented by a Smeech expression is as follows:
1) An integer represents itself
2) With probability p, (p e1 e2) represents x+y where x is the value of e1 and y is the value of e2; otherwise it represents x-y.
Given a Smeech expression, what is its expected value?

输入:

Input consists of several Smeech expressions, one per line, followed by a line containing ().

输出:

For each expression, output its expected value to two decimal places.

样例输入:

7
(.5 3 9)
()

样例输出:

7.00
3.00


主要学习一下sscanf函数的强大用法!

#include<stdio.h>
#include<string.h>
#include<math.h>
char s[1248];
double Getanswer(char *s)
{
  double ans,p,x,y;
  int i,j,n;
  if(s[0]!='(')//输入的就是一个数字
  {
    sscanf(s,"%lf",&ans);//字符串转换为double
    return ans;
  }
  sscanf(s+1,"%lf",&p);
  i=0;
  while(s[i++]!=' ');       //while(s[i]!=' ')    {  i++;   }
  if(s[i]!='(')
  {
    sscanf(s+i,"%lf",&x);
    while(s[i++]!=' ');
    if(s[i]!='(')   sscanf(s+i,"%lf",&y);
    else             y=Getanswer(s+i);
  }
  else
  {
     n=1;
     for(j=i+1;n;j++)//左右括号的析取抵消
      {
        if(s[j]=='(')   ++n;
        if(s[j]==')')     --n;
      }
      s[j]='\0';
      x=Getanswer(s+i);
      if(s[j+1]=='(')    y=Getanswer(s+j+1);
      else              sscanf(s+j+1,"%lf",&y);
  }
  return x+(p+p-1)*y;
}
int main()
{
   while(gets(s))
    {
     if(strcmp(s,"()")==0)     break;
      printf("%.2lf\n",Getanswer(s));
    }
}