SPOJ MCARDS

本文介绍了一款针对四岁儿童Maverick的卡片游戏策略,旨在通过编程解决如何最有效地排列卡片的问题。通过输入卡片的颜色和数值,输出最少的移动次数来完成排序。详细解析了使用动态规划和最长上升子序列的方法进行求解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值