HDOJ 5125 magic balls DP


DP

magic balls

Time Limit: 6000/3000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 561    Accepted Submission(s): 168


Problem Description
The town of W has N people. Each person takes two magic balls A and B every day. Each ball has the volume  ai  and  bi . People often stand together. The wizard will find the longest increasing subsequence in the ball A. The wizard has M energy. Each point of energy can change the two balls’ volume.( swap(ai,bi) ).The wizard wants to know how to make the longest increasing subsequence and the energy is not negative in last. In order to simplify the problem, you only need to output how long the longest increasing subsequence is.
 

Input
The first line contains a single integer  T(1T20) (the data for  N>100  less than 6 cases), indicating the number of test cases.
Each test case begins with two integer  N(1N1000)  and  M(0M1000) ,indicating the number of people and the number of the wizard’s energy. Next N lines contains two integer  ai  and  bi(1ai,bi109) ,indicating the balls’ volume.
 

Output
For each case, output an integer means how long the longest increasing subsequence is.
 

Sample Input
   
   
   
   
2 5 3 5 1 4 2 3 1 2 4 3 1 5 4 5 1 4 2 3 1 2 4 3 1
 

Sample Output
   
   
   
   
4 4
 

Source
BestCoder Round #20
 



#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

const int maxn=1111;

int n,m;
int a[maxn],b[maxn];
int dp[maxn][maxn][2];

int main()
{
	int T_T;
	scanf("%d",&T_T);
	while(T_T--)
	{
		scanf("%d%d",&n,&m);
		for(int i=1;i<=n;i++)
		{
			scanf("%d%d",a+i,b+i);
		}
		memset(dp,-1,sizeof(dp));
		dp[0][0][0]=0;
		for(int i=1;i<=n;i++)
		{
			dp[i][0][0]=1; dp[i][1][1]=1;
			for(int j=1;j<i;j++)
			{
				int e=min(j,m);
				if(a[i]>a[j])
				{
					for(int k=0;k<=e;k++)
					{
						if(dp[j][k][0]>=0) 
							dp[i][k][0]=max(dp[i][k][0],dp[j][k][0]+1);
					}
				}
				if(a[i]>b[j])
				{
					for(int k=0;k<=e;k++)
					{
						if(dp[j][k][1]>=0) 
							dp[i][k][0]=max(dp[i][k][0],dp[j][k][1]+1);
					}
				}
				if(b[i]>a[j])
				{
					for(int k=0;k<=e;k++)
					{
						if(dp[j][k][0]>=0) 
							dp[i][k+1][1]=max(dp[i][k+1][1],dp[j][k][0]+1);
					}
				}
				if(b[i]>b[j])
				{
					for(int k=0;k<=e;k++)
					{
						if(dp[j][k][1]>=0) 
							dp[i][k+1][1]=max(dp[i][k+1][1],dp[j][k][1]+1);
					}
				}
			}
		}
		int ans=1;
		for(int i=1;i<=n;i++)
		{
			int e=min(i,m);
			for(int j=0;j<=e;j++)
			{
				ans=max(ans,max(dp[i][j][0],dp[i][j][1]));
			}
		}
		printf("%d\n",ans);
	}
	return 0;
}



你可能感兴趣的:(HDOJ 5125 magic balls DP)