题意:求矩阵相乘的最佳花括号的方式并打印出来
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<vector>
#include<cmath>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<algorithm>
using namespace std;
const int INF=0x3f3f3f3f;
const int maxn=110;
struct node
{
int n,m;
}a[maxn];
int N;
int dp[maxn][maxn];
int path[maxn][maxn];
void dfs(int x,int y)
{
if(x==y)
{
printf("A%d",x);
return;
}
printf("(");
dfs(x,path[x][y]);
printf(" x ");
dfs(path[x][y]+1,y);
printf(")");
}
int main()
{
int cas=1;
while(scanf("%d",&N)!=EOF,N)
{
for(int i=1;i<=N;i++)scanf("%d%d",&a[i].n,&a[i].m);
memset(dp,INF,sizeof(dp));
memset(path,-1,sizeof(path));
for(int i=1;i<=N;i++)dp[i][i]=0,path[i][i]=i;
for(int len=1;len<=N;len++)
{
for(int i=1;i+len-1<=N;i++)
{
int j=i+len-1;
for(int k=i;k<j;k++)
{
if(dp[i][k]+dp[k+1][j]+a[i].n*a[k].m*a[j].m<dp[i][j])
{
dp[i][j]=dp[i][k]+dp[k+1][j]+a[i].n*a[k].m*a[j].m;
path[i][j]=k;
}
}
}
}
printf("Case %d: ",cas++);
dfs(1,N);
printf("\n");
}
return 0;
}