Matrix Chain Multiplication

ACM题http://uva.onlinejudge.org/external/4/442.html

 #include<iostream>
#include<stack>
#include<list>
#include<string>
#include <stdio.h>
#include <stdlib.h>

using namespace std;
typedef struct Matrixs
{
 char name;
 int row;
 int column;
}MATRIXS;
int main()
{
    int count,i,valid,element,temp4,temp1,temp2,temp3;
size_t pos1,pos2;
string str1,str2;
 string input;
    getline(cin,input);
 count = atoi(input.c_str());
 stack<char> matrix;
 list<Matrixs> in;
 list<Matrixs>::iterator iter;
    while(count--)
    {
  Matrixs tmp;
  getline(cin, input);    //input the first part
  tmp.name = input.at(0);
  pos1 = input.find(' ');
  pos2 = input.find_last_of(' ');
  str1 = input.substr(pos1,pos2);
  str2 = input.substr(pos2);
  tmp.row = atoi(str1.c_str());
  tmp.column = atoi(str2.c_str());
  in.push_back(tmp);
    }
 
 while(1)                       //the second part
 {
  element = 0;
  getline(cin,input);
  if(0 == input.size())
  {
   break;
  }
  else
  {
   while(!matrix.empty())
    matrix.pop();
   valid = 1;

   for(i = 0; valid&&i<input.size(); ++i)
   {
    char c = input.at(i);
    if('(' == c)matrix.push(c);
    else  if(')' == c)
    {
     temp1 = matrix.top();
     matrix.pop();
     temp2 = matrix.top();
     matrix.pop();
     temp3 = matrix.top();
     matrix.pop();
     temp4 = matrix.top();

     matrix.pop();
     matrix.pop();
     if(temp2 != temp3)
     {
      valid = 0;
     }
     else
     {
      matrix.push(temp4);
      matrix.push(temp1);
      element += temp1*temp2*temp4;
     }
    }

      for(iter= in.begin();iter != in.end();++iter)
      {
       if(c == (*iter).name)
       {
                       matrix.push((*iter).row);
        matrix.push((*iter).column);
       } 
      }
   }
   if(0 == valid)
   {
    cout << "error" <<endl;
   }
   else
   {
    cout << element <<endl;
   }
  }
 }
 return 0;  
}

发现用了cin>>,再用getline(cin,input),就不能输入了,最后全改成getline(cin,input),就没问题了,呵呵。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值