这个思路很好
http://www.cppblog.com/wuxu/archive/2011/11/23/160794.aspx
类似于上一个题目,但有所不同
设计一个struct保存原始值和叠加以后的值(检验是否超出)
每碰到一个正数,便对于栈中数据进行处理,这个时候用到struct中记录的数据比较是否超出大小范围
#include <iostream>
#include <sstream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <string>
#include <vector>
#include <set>
#include <cctype>
#include <algorithm>
#include <cmath>
#include <deque>
#include <queue>
#include <map>
#include <stack>
#include <iomanip>
using namespace std;
///
#define INF 0xffffff7
#define maxn 300
///
struct MyNum
{
int Original;
int AfterAdd;
};
vector<int> num;
stack<MyNum> stk;
int main()
{
///
int positive, negetive;
string line;
while (getline(cin, line))
{
num.clear();
while (!stk.empty())
stk.pop();
istringstream stream(line);
int temp;
positive = negetive = 0;
bool Isok = true;
while(stream >> temp)
{
num.push_back(temp);
if (temp > 0)
{
positive++;
}
else
negetive++;
if (positive > negetive)
{
Isok = false;
break;
}
}
if (!Isok || (num.size() % 2 != 0))
{
cout << ":-( Try again." << endl;
continue;
}
vector<int>::iterator it = num.begin();
MyNum tempNum;
while (it != num.end())
{
int test;
test = *it;
if (test < 0)
{
tempNum.Original = tempNum.AfterAdd = test;
stk.push(tempNum);
it++;
continue;
}
else
{
if (!stk.empty() && (stk.top().Original + test == 0))
{
stk.pop();
if (!stk.empty())
{
tempNum = stk.top();
stk.pop();
tempNum.AfterAdd += test;
if (tempNum.AfterAdd >= 0)
{
Isok = false;
break;
}
stk.push(tempNum);
}
else if ((it + 1) != num.end())
{
Isok = false;
break;
}
}
else
{
Isok = false;
break;
}
it++;
}
}
if (Isok)
{
cout << ":-) Matrioshka!" << endl;
}
else
cout << ":-( Try again." << endl;
}
///
return 0;
}