Monday, 24 February 2014

UVA Problem ID 442 (Matrix Chain Multiplication)

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;


public class Main {
	public static void main (String args[]) throws IOException
	{
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		StringBuilder sb=new StringBuilder(1000);
		int no_of_matrices=Integer.parseInt(br.readLine());
		Matrix matrices[]=new Matrix[26];
		for (int i = 0; i  st=new Stack();
			int totalcost=0;
			for (int i = 0; i < input.length(); i++) {
				if(input.charAt(i)=='(')
				{
					//do nothing
				}
				else if(input.charAt(i)==')')
				{
					
					Matrix b=(Matrix) st.pop();
					Matrix a=(Matrix) st.pop();

					if(a.column!=b.row)
					{
						sb.append("error\n");
						flag=false;
						break;
					}
					else
					{
						totalcost+=a.row*a.column*b.column;
						st.push(new Matrix('t',a.row,b.column));		
					}
				}
				else
				{
					st.push(matrices[input.charAt(i)-65]);
				}
			}
			if(st.size()>2)
			{
				sb.append("error\n");
				flag=false;
			}
			else if(!st.isEmpty() && st.size()==2)
			{
				
				Matrix b=(Matrix) st.pop();
				Matrix a=(Matrix) st.pop();	
				if(a.column!=b.row)
				{
					sb.append("error\n");
					flag=false;
				}
				else
				{
					totalcost+=a.row*a.column*b.column;				
				}
			}
			if(flag)
				sb.append(totalcost+"\n");
		}
		System.out.print(sb);
	}
}
class Matrix
{
	public int row;
	public int column;
	public char name;
	
	public Matrix(char name,int row,int column)
	{
		this.name=name;
		this.row=row;
		this.column=column;
	}
}

Previous Post
Next Post

0 comments:

Advertisement