http://www.luogu.org/problem/show?pid=1282

設f[i][j]為前i個骨牌差值為j的最小翻牌次數

初始值全部賦值為∞,然後f[1][a[1]-b[1]]=0, f[1][b[1]-a[i]]=1;對應於第一張牌不翻和翻

狀態轉移方程:

f[i][j] = min(f[i-1][j-(a[i]-b[i])], f[i-1][j-(b[i]-a[i])]+1);

對應於不翻和翻

由於有負數,要加上一個較大的中間數把所有的值轉為正數,然後找答案在f[n]裡找,從較大的中間數開始雙向查詢,最早找到的就是答案。

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cstdlib>
#define ms(i,j) memset(i, j, sizeof(i));
using namespace std;
int a[1005];
int b[1005];
int f[1003][10003];
const int INF = 100000000;
const int NO = 5000;
int main()
{
	int n;
	scanf("%d", &n);
	for (int i=1;i<=n;i++) scanf("%d%d", &a[i], &b[i]);
	for (int i=0;i<=n;i++) for (int j=-5*n;j<=5*n;j++) f[i][j+NO] = INF;
	f[1][a[1]-b[1]+NO]=0, f[1][b[1]-a[1]+NO]=1;
	for (int i=1;i<=n;i++)
	{
		for (int j=-5*n;j<=5*n;j++)
		{
			f[i][j+NO] = min(f[i][j+NO], f[i-1][j-(a[i]-b[i])+NO]);
			f[i][j+NO] = min(f[i][j+NO], f[i-1][j-(b[i]-a[i])+NO]+1);
		}
	}
	for (int i=NO,j=NO;i<=5*n+NO||j>=0;i++,j--)
	if (f[n][i]!=INF){ printf("%d\n", f[n][i]);break;}
	else if (f[n][j]!=INF) {printf("%d\n", f[n][j]);break;}
	return 0;
}