poj 1717 Dominoes(dp)

Dominoes
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 6728 Accepted: 2232

Description

A domino is a flat, thumbsized tile, the face of which is divided into two squares, each left blank or bearing from one to six dots. There is a row of dominoes laid out on a table: 

The number of dots in the top line is 6+1+1+1=9 and the number of dots in the bottom line is 1+5+3+2=11. The gap between the top line and the bottom line is 2. The gap is the absolute value of difference between two sums. 

Each domino can be turned by 180 degrees keeping its face always upwards. 

What is the smallest number of turns needed to minimise the gap between the top line and the bottom line? 

For the figure above it is sufficient to turn the last domino in the row in order to decrease the gap to 0. In this case the answer is 1. 
Write a program that: computes the smallest number of turns needed to minimise the gap between the top line and the bottom line.

Input

The first line of the input contains an integer n, 1 <= n <= 1000. This is the number of dominoes laid out on the table. 

Each of the next n lines contains two integers a, b separated by a single space, 0 <= a, b <= 6. The integers a and b written in the line i + 1 of the input file, 1 <= i <= 1000, are the numbers of dots on the i-th domino in the row, respectively, in the top line and in the bottom one. 

Output

Output the smallest number of turns needed to minimise the gap between the top line and the bottom line.

Sample Input

4
6 1
1 5
1 3
1 2

Sample Output

1

Source

[Submit]   [Go Back]   [Status]   [Discuss]


题解:dp

f[i][j]表示到第i列第一行-第二行的差值为j的最少交换次数。

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<cstring>
#define N 1003
using namespace std;
int f[N][N*10],a[N],b[N],n;
int main()
{
	freopen("a.in","r",stdin);
	freopen("my.out","w",stdout);
	scanf("%d",&n);
	for (int i=1;i<=n;i++)
	 scanf("%d%d",&a[i],&b[i]);
	int base=5000;
	memset(f,127/3,sizeof(f)); int inf=f[0][0];
	if (a[1]==b[1]) f[1][a[1]-b[1]+base]=0;
	else f[1][a[1]-b[1]+base]=0,f[1][b[1]-a[1]+base]=1;
	for (int i=2;i<=n;i++)
	 for (int j=-5000;j<=5000;j++)
	  {
	  	f[i][j+base]=min(f[i][j+base],f[i-1][j+b[i]-a[i]+base]);
	  	f[i][j+base]=min(f[i][j+base],f[i-1][j+a[i]-b[i]+base]+1);
	  }
	int ans=1000000000,ansx=1000;
	for (int i=0;i<=2*base;i++)
	 if (f[n][i]!=inf){
	 	int t=i-base;
	 	if (ans>t) ans=min(ans,abs(t)),ansx=f[n][i];
	 	else if (ans==t) ansx=min(ansx,f[n][i]);
	 }
	printf("%d\n",ansx);
}

刚开始还写了一种不科学的思路。f[i]表示到第i列取到差值最小时第一行的值,g[i]为此时对应的反转个数。这样每次枚举每一列和最近的反转列(转移时保证i反转)。但是这样是存在问题的,因为有可能存在情况,要求前面的必须差值变大,后面才能将其变小。

4
2 1
1 3
4 1
6 1

这组样例就能卡掉上面的那种方法。。。。。


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值