UVa 442 - Matrix Chain Multiplication

用结构体储存矩形的信息。然后想法和括号的想法相同。!=‘)’,则s.push。若==‘)’。则取出两个 s.top ( )。切记先取出的是第二个矩形。先进后出。然后比较两个的 行和列

然后计算。最后更新栈的top就是。计算后这个矩形的的 行 列 和 代号 ( 不知道叫什么好了 )



// File Name: UVa442.cpp
// Author: Toy
// Created Time: 2013年03月28日 星期四 18时59分17秒

#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <cctype>
#include <cmath>
#include <string>
#include <algorithm>
#include <cstdlib>
#include <iomanip>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <utility>
#define L(x) x << 1
#define R(x) x << 1 | 1

using namespace std;

struct Matrix {
    char ch;
    int row, cul;
}matrix[55];

int Case, cmp1, cmp2, ans;
char rec[100], tmp1, tmp2, tmp;

int main ( ) {
    scanf ( "%d", &Case  );
    for ( int i = 0; i < Case; ++i ) {
	scanf ( "%c", &matrix[i].ch );
	getchar ( );
	scanf ( "%d%d", &matrix[i].row, &matrix[i].cul );
	getchar ( );
    }
    while ( fgets ( rec, 100, stdin ) != NULL ) {
	tmp = Case;
	//printf ( "00\n" );
	//puts ( rec );
	ans = 0;
	int len = strlen ( rec );
	rec[len--] = '\0';
	stack < char > s;
	for ( int i = 0; rec[i] != '\0'; ++i ) {
	    if ( rec[i] != ')' ) s.push ( rec[i] );
	    if ( rec[i] == ')' ) {
		tmp2 = s.top ( );
		s.pop ( );
		tmp1 = s.top ( );
		s.pop ( );
		s.pop ( );
		cmp1 = tmp1 - 'A';
		cmp2 = tmp2 - 'A';
		if ( matrix[cmp1].cul == matrix[cmp2].row ) {
		    ans += matrix[cmp1].row * matrix[cmp1].cul * matrix[cmp2].cul;
		    matrix[tmp].row = matrix[cmp1].row;
		    matrix[tmp].cul = matrix[cmp2].cul;
		    matrix[tmp].ch = tmp + 'A';
		    s.push ( matrix[tmp].ch );
		    tmp++;
		}
		else {
		    printf ( "error\n" );
		    ans = -1;
		    break;
		}
	    }
	}
	if ( ans != -1 ) printf ( "%d\n", ans );
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值