您的位置:首页 > 其它

HDU 1082 矩阵乘法次数计算 写了半天搞定,很有成就感啊

2012-09-24 15:05 369 查看
这个思想本来不难,实现起来感觉有点复杂,容易出错。调试了搞定。有成就感。、

#include <iostream>
#include <stack>
#include <vector>
#include <algorithm>
using namespace std;
int row[26], col[26];
char str[10000];
int count(int *a, int n)
{
int flag = 0;
if(n == 2)
return 0;
for(int i = 1 ; i < n-1; i += 2)
{
if(a[i] != a[i+1])
{
flag = 1;
break;
}
}
if(flag == 1)
return -1;
int mul = a[0];
for(int i = 1; i < n; i += 2 )
{
mul *= a[i];
}
return mul;
}
int main()
{
int t;
cin >> t;
char temp;
for(int i = 0 ;i < t ; i++)
{
getchar(); //重要
scanf("%c", &temp);
scanf("%d%d", &row[temp-'A'], &col[temp-'A']);
}
getchar();
while(gets(str))
{
int n = strlen(str);
if(n == 1)
{
cout << "0" << endl;
continue;
}

stack<char> stk;
int sum = 0;
int flag = 0;
for(int i = 0; i < n; i++)
{
if(str[i] != ')' )
{
if(isalpha(str[i]))
{
stk.push((char)row[str[i] - 'A']);
stk.push((char)col[str[i] - 'A']);
}
if(str[i] == '(')
stk.push('(');
}
if(str[i] == ')' || i == n-1)
{
int cnt = 0;
int a[10000];
while(!stk.empty())
{
if(stk.top() == '(')
{
stk.pop();
break;
}
a[cnt++] = (int)stk.top();
stk.pop();
}
reverse(a, a+ cnt);
if(!stk.empty())
{
stk.push(a[0]);
stk.push(a[cnt-1]);
}
int mul  = 1;
mul = count(a, cnt);
if(mul == -1)
{
flag = 1;
break;
}
else
sum += mul;
}
if(flag == 1)
break;
}
if(flag == 1)
cout << "error" << endl ;
else
cout << sum << endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: