magic balls
Time Limit: 6000/3000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 904 Accepted Submission(s): 277
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(1≤T≤20)
(the data for
N>100
less than 6 cases), indicating the number of test cases.
Each test case begins with two integer N(1≤N≤1000) and M(0≤M≤1000) ,indicating the number of people and the number of the wizard’s energy. Next N lines contains two integer ai and bi(1≤ai,bi≤109) ,indicating the balls’ volume.
Each test case begins with two integer N(1≤N≤1000) and M(0≤M≤1000) ,indicating the number of people and the number of the wizard’s energy. Next N lines contains two integer ai and bi(1≤ai,bi≤109) ,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
题意:每个人有两个球,对第一个球求最长上升子序列,第一个球和第二个球可以交换m次
思路:参考此人。m表示取到最优值时所花的交换个数。
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
int n,m;
#define N 1010
int dp[N][2],a[N],b[N];
int num[N][2];
void f(int i,int j,int v,int v1)
{
dp[i][v]=dp[j][v1]+1;
num[i][v]=num[j][v1];
if(v==1) num[i][v]++;
}
void solve()
{
memset(dp,0,sizeof(dp));
memset(num,0,sizeof(num));
for(int i=1;i<=n;i++)
{
for(int j=0;j<i;j++)
{
if(a[i]>a[j]&&(dp[i][0]<dp[j][0]+1||(dp[i][0]==dp[j][0]+1&&num[i][0]>num[j][0])))
f(i,j,0,0);
if(a[i]>b[j]&&(dp[i][0]<dp[j][1]+1||(dp[i][0]==dp[j][1]+1&&num[i][0]>num[j][1])))
f(i,j,0,1);
if(b[i]>a[j]&&(dp[i][1]<dp[j][0]+1||(dp[i][1]==dp[j][0]+1&&num[i][1]>num[j][0]+1)))
f(i,j,1,0);
if(b[i]>b[j]&&(dp[i][1]<dp[j][1]+1||(dp[i][1]==dp[j][1]+1&&num[i][1]>num[j][1]+1)))
f(i,j,1,1);
}
}
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
scanf("%d %d",&n,&m);
for(int i=1;i<=n;i++)
scanf("%d %d",&a[i],&b[i]);
solve();
int ans=0;
for(int i=1;i<=n;i++)
{
if(num[i][0]>m) ans=max(ans,dp[i][0]-num[i][0]+m);
else ans=max(ans,dp[i][0]);
if(num[i][1]>m) ans=max(ans,dp[i][1]-num[i][1]+m);
else ans=max(ans,dp[i][1]);
}
printf("%d\n",ans);
}
return 0;
}