题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=1561
题意:给出n个点的权值,构造一棵特殊的哈夫曼树满足:(1)叶子节点从左到右依次是n个点给出的顺序;(2)每个点的代价为深度乘以权值,(3)总代价最小?
思路:f[i][j]=min(f[i][k]+f[k+1][j]+sum[j]-sum[i-1])。
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <cmath>
#include <vector>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <map>
#define max(x,y) ((x)>(y)?(x):(y))
#define min(x,y) ((x)<(y)?(x):(y))
#define abs(x) ((x)>=0?(x):-(x))
#define i64 long long
#define u32 unsigned int
#define u64 unsigned long long
#define clr(x,y) memset(x,y,sizeof(x))
#define CLR(x) x.clear()
#define ph(x) push(x)
#define pb(x) push_back(x)
#define Len(x) x.length()
#define SZ(x) x.size()
#define PI acos(-1.0)
#define sqr(x) ((x)*(x))
#define MP(x,y) make_pair(x,y)
#define EPS 1e-9
#define FOR0(i,x) for(i=0;i<x;i++)
#define FOR1(i,x) for(i=1;i<=x;i++)
#define FOR(i,a,b) for(i=a;i<=b;i++)
#define FORL0(i,a) for(i=a;i>=0;i--)
#define FORL1(i,a) for(i=a;i>=1;i--)
#define FORL(i,a,b)for(i=a;i>=b;i--)
#define rush(n) for(scanf("%d",&C);C--;)
#define Rush(n) while(scanf("%d",&n)!=-1)
using namespace std;
void RD(int &x){scanf("%d",&x);}
void RD(u32 &x){scanf("%u",&x);}
void RD(double &x){scanf("%lf",&x);}
void RD(int &x,int &y){scanf("%d%d",&x,&y);}
void RD(u32 &x,u32 &y){scanf("%u%u",&x,&y);}
void RD(double &x,double &y){scanf("%lf%lf",&x,&y);}
void RD(int &x,int &y,int &z){scanf("%d%d%d",&x,&y,&z);}
void RD(int &x,int &y,int &z,int &t){scanf("%d%d%d%d",&x,&y,&z,&t);}
void RD(u32 &x,u32 &y,u32 &z){scanf("%u%u%u",&x,&y,&z);}
void RD(double &x,double &y,double &z){scanf("%lf%lf%lf",&x,&y,&z);}
void RD(char &x){x=getchar();}
void RD(char *s){scanf("%s",s);}
void RD(string &s){cin>>s;}
void PR(int x) {printf("%d\n",x);}
void PR(int x,int y) {printf("%d %d\n",x,y);}
void PR(int x,int y,int z) {printf("%d %d %d\n",x,y,z);}
void PR(i64 x) {printf("%lld\n",x);}
void PR(u32 x) {printf("%u\n",x);}
void PR(double x) {printf("%.5lf\n",x);}
void PR(char x) {printf("%c\n",x);}
void PR(char *x) {printf("%s\n",x);}
void PR(string x) {cout<<x<<endl;}
const i64 inf=((i64)1)<<60;
const int INF=1000000000;
const int N=2005;
int s[N][N],n,a[N];
i64 f[N][N],sum[N];
void DFS(int x,int L,int R)
{
if(L>=R) return;
if(x<=s[L][R]) putchar('0'),DFS(x,L,s[L][R]);
else putchar('1'),DFS(x,s[L][R]+1,R);
}
int main()
{
Rush(n)
{
int i,j,k,L;
i64 temp;
FOR1(i,n)
{
RD(a[i]);
sum[i]=sum[i-1]+a[i];
s[i][i]=i;
f[i][i]=a[i];
}
for(L=2;L<=n;L++) for(i=1;i+L-1<=n;i++)
{
j=i+L-1; f[i][j]=inf;
FOR(k,s[i][j-1],s[i+1][j])
{
temp=f[i][k]+f[k+1][j]+sum[j]-sum[i-1];
if(temp<f[i][j]) f[i][j]=temp,s[i][j]=k;
}
}
FOR1(i,n) DFS(i,1,n),puts("");
}
return 0;
}