【UVA10003】切木棍 dp

题目

紫书说的很详细了

#include
#include
#include
#include
#define inf 0x3f3f3f3f
using namespace std;

int dp[501][501],a[1005];
int n,m,len;

int read()
{
	char ch=getchar();int ret=0,f=1;
	while(ch<'0'||ch>'9') {if (ch=='-') f=-1;ch=getchar();}
	while(ch>='0'&&ch<='9'){ret=ret*10+ch-'0';ch=getchar();}
	return f*ret;
}

int main()
{
	while(1)
	{
		len=read();if (!len) break;
		n=read();	
		for (int i=1;i<=n;i++) a[i]=read();
		a[0]=0;a[n+1]=len;

		for (int l=1;l<=n+1;l++)
		{
			for (int i=0;i+l<=n+1;i++)
			{
				int j=i+l,temp=inf;
				for (int k=i+1;k<=j-1;k++)
					temp=min(temp,dp[i][k]+dp[k][j]+a[j]-a[i]);
				if (temp!=inf) dp[i][j]=temp;
			}

		}
		printf("The minimum cutting is %d.\n",dp[0][n+1]);
	}

	return 0;
}

你可能感兴趣的:(UVa,动态规划-简单dp)