这篇博客是从旧博客 WordPress 迁移过来,内容可能存在转换异常。
传送门:http://acm.hdu.edu.cn/showproblem.php?pid=3347
模拟水题,注意sscanf用法。
考虑几种情况: 1.变量 2. =/? 3. +/- 4. 正数 5负数
以下是代码,有得有点乱,各种添加。。。
#include
#include
#include
#include
#include
using namespace std;
map var;
int T;
int n;
char str[1000], str1[1000];
int main()
{
//freopen("input.txt", "r", stdin);
string s, s1;
int tmp;
cin >> T;
int ans;
int mark;
int v;
while(T--)
{
mark = 1;
ans = 0;
cin >> n;
for(int i=0 ;i> s;
cin >> s1;
cin >> tmp;
var[s] = tmp;
//cout << s << ": " << var[s] << endl;
}
getchar();
gets(str);
//cout << str << endl;
for (int i = 0; i < strlen(str) ; i += strlen(str1)+1 )
{
sscanf(str+i, "%s", str1);
//cout << str1 << endl;
if(str1[0] == '=')
continue;
else if(str1[0] == '?')
;
else if(str1[0] == '+' || (str1[0] == '-' && strlen(str1)==1))
{
if(str1[0] == '+')
mark = 1;
else
mark = -1;
}
else if(str1[0]>='a' && str1[0]<='z')
{
//cout << "var[" << str1 << "]=" << var[str1] << endl;
ans += mark*var[str1];
//cout << "ans=" << ans << endl;
mark = 0;
}
else
{
if(str1[0] == '-')
{
mark *= -1;
sscanf(str1+1, "%d", &v;);
}
else
sscanf(str1, "%d", &v;);
//cout << "v=" << v << endl;
ans += mark*v;
//cout << "ans=" << ans << endl;
mark = 0;
}
}
cout << ans << endl;
//cout << "--------------------------------\n";
}
return 0;
}
下面把sscanf用法贴以下(MSDN):
int sscanf( const char *buffer, const char *format [, argument ] ... ); buffer > Stored data > format > Format-control string. For more information, see Format Specifications. > argument > Optional arguments > The sscanf function reads data from buffer into the location given by each argument. Every argument must be a pointer to a variable with a type that corresponds to a type specifier in format. The format argument controls the interpretation of the input fields and has the same form and function as the format argument for the scanf function. If copying takes place between strings that overlap, the behavior is undefined.