1. 程式人生 > >poj1772線性dp

poj1772線性dp

一般現代模型,不行上解題表。嗯,只要發現除了第二個以外其他數前面都可以是正或負就好了,可以dp。證明用歸納法很容易的

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
using namespace std;
int dp[110][21000];
int a[120];
int real;
char nob[120];
int maxx;
int n, t;
int main()
{
	    scanf("%d%d", &n, &t);
		maxx = 0;
		for (int i = 1; i <= n; i++)
		{
			scanf("%d", &a[i]);
			maxx += a[i];
		}
		dp[1][a[1] + maxx+1] = 1;
		dp[2][a[1] - a[2] + maxx+1] = a[1] + maxx+1;
		for (int i = 3; i <= n; i++)
		{
			for (int j = 1; j < a[i]+1; j++)
			{
				if (dp[i - 1][j + a[i]])
					dp[i][j] = j + a[i];
			}
			for (int j = a[i]+1; j <= 2 * maxx+1; j++)
			{
				if (dp[i - 1][j + a[i]])
					dp[i][j] = j + a[i];
				else
				{
					if (dp[i - 1][j - a[i]])
						dp[i][j] = j - a[i];
				}
			}
		}
		int tempj = t + maxx+ 1;
		for (int i = n; i >= 2; i--)
		{
			if (dp[i][tempj] > tempj)
				nob[i] = '-';
			else
				nob[i] = '+';
			tempj = dp[i][tempj];
		}
		int real = 1;
		nob[n + 1] = '\0';
		while (real < n)
		{
			if (nob[real + 1] == '-' && (nob[real + 2] == '-' || nob[real + 2] == '\0'))
			{
				printf("1\n");
				real++;
			}
			else
			{
				int tempj = real + 1;
				while (nob[tempj + 1] == '+')
				{
					printf("2\n");
					tempj++;
				}
				printf("1\n");
				real = tempj;
			}
		}
		return 0;

}