SPOJ MCARDS

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;
}


發佈了123 篇原創文章 · 獲贊 1 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章