Dave’s little son Maverick likes to play card games, but being only fouryears old, he always lose when playing with his older friends. Also,arranging cards in his hand is quite a problem to him.
When Maverick gets his cards, he has to arrange them in groups so thatall the cards in a group are of the same color. Next, he has to sort the cards in each group by their value – card with lowest value shouldbe the leftmost in its group. Of course, he has to hold all the cards in his hand all the time.
He has to arrange his cards as quickly as possible, i.e. making as few moves as possible. A move consists of changing a position of one of his cards.
Write a program that will calculate the lowest number of moves needed to arrange cards.
Input
The first line of input file contains two integers C, number of colors(1 ≤ C ≤ 4), and N, number of cards of the same color (1 ≤ N ≤ 100), separated by a space character.
Each of the next C*N lines contains a pair of two integers X and Y, 1 ≤ X ≤ C, 1 ≤ Y ≤ N, separated by a space character.
Numbers in each of those lines determine a color (X) and a value (Y) of a card dealt to little Maverick. The order of lines corresponds to the order the cards were dealt to little Maverick.No two lines describe the same card.
Output
The first and only line of output file should contain the lowest number of moves needed to arrange the cards as described above.
Sample
CARDS.IN 2 2 2 1 1 2 1 1 2 2 CARDS.OUT 2 CARDS.IN 4 1 2 1 3 1 1 1 4 1 CARDS.OUT 0 CARDS.IN 3 2 3 2 2 2 1 1 3 1 2 1 1 2 CARDS.OUT 2
解析
动规LIS。
求最长上升子序列,然后用N*M-longest。比较特别的是color的优先级会变,所以我将color的优先级做了个全排列。因为序列是二元组,所以g存的是p的编号。
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cstring>
using namespace std;
struct node
{
int x,y;
bool operator<(const node &a) const//以x为关键y为次关键字排序
{
if(x==a.x) return y<a.y;//y升序
return x<a.x;//x升序
}
} p[500];
int N,M,dp[500],g[500];
//dp[i]表示以第i张牌结尾的上升子序列长度
//g[i]表示序列长度为i的序列最小以p[g[i]]结尾
void readdata()
{
for(int i=1;i<=N*M;i++)
scanf("%d%d",&p[i].x,&p[i].y);
p[N*M+1].x=0x3f3f3f3f;p[N*M+1].y=0x3f3f3f3f;
//for(int i=1;i<=N+1;i++) printf("%d ",p[i].y);printf("\n");
}
int find(node x)
{
int l=1,r=N*M+2;
while(l<r)//单增
{
int mid=(l+r)>>1;
if(g[mid]==0x3f3f3f3f) {r=mid;continue;}
if(p[g[mid]]<x) l=mid+1;
else r=mid;
}
return l;
}
void dynamic_planning()
{
memset(g,0x3f,sizeof(g));//g-->id
for(int i=1;i<=N*M+1;i++)
{
int k=find(p[i]);
dp[i]=k;
g[k]=i;
}
printf("%d\n",N*M-(dp[N*M+1]-1));
}
int main()
{
scanf("%d%d",&N,&M);
readdata();
dynamic_planning();
while(1);
return 0;
}