zju/zoj 1276 Optimal Array Multiplication Sequence(dp)

#include<cstdio>
#include<cstring>
#define MIN(a,b) (a)<(b)?(a):(b)
#define M 100

int position[M][M];
void putpath(int i,int j){
	if( i>j)
		return ;
	if(position[i][j]){
		printf("(");
		putpath(i,position[i][j]);
		printf(" x ");
		putpath(position[i][j]+1,j);
		putchar(')');
	}
	else
		printf("A%d",i);
}
int main(){
	int n,Case=0;
	while(~scanf("%d",&n) && n){

		int numa[M],numb[M],dp[M][M],i,j,k;
		
		memset(dp,0,sizeof(dp));
		memset(position,0,sizeof(position));

		for(i=1;i<=n;i++)
			scanf("%d %d",&numa[i],&numb[i]);


		for(k=1;k<n;k++){

			for(i=1;i+k<=n;i++){
				int t=1<<30;
				int j=i+k;
				for(int p=i;p<j;p++){

					t=MIN(t,dp[i][p]+dp[p+1][j]+numa[i]*numa[p+1]*numb[j]);

					if( t<dp[i][j] || (i!=j && !dp[i][j]) )
					dp[i][j]=t,position[i][j]=p;
				}

			}
		}

	printf("Case %d: ",++Case);

	putpath(1,n);
	putchar('\n');
		
	}
	return 0;
}

你可能感兴趣的:(zju/zoj 1276 Optimal Array Multiplication Sequence(dp))