状压DP LIGHTOJ 1194 Colored T-Shirts

本文介绍了一种求解让序列中的相同数字聚集在一起所需的最小交换次数的算法。通过预处理和动态规划的方法,该算法可以高效地解决给定序列问题。适用于序列长度在1到1e5之间,数字范围在1到16的情况。

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

给你一串序列,求让这个序列相同的数字放在一起的最少交换次数

序列中的数字范围1-16

序列中数字个数1-1e5

思路:

首先要预处理 cnt[i][j] 表示数字j放在数字i前所要用到的交换次数

然后枚举每种情况1<<m

比如:m个零

000000000 第i个位置为0,表示此时数字i是乱序的,反之是放好的

代码如下

/********************************************
Author         :Crystal
Created Time   :
File Name      :
********************************************/
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <climits>
#include <string>
#include <vector>
#include <cmath>
#include <stack>
#include <queue>
#include <set>
#include <map>
using namespace std;
int cnt[20][20];
int pre[20];
long long dp[1<<16];
int nmin;
#define inf 0x3f3f3f3f
int main()
{
	freopen("in.txt","r",stdin);
	//freopen("out.txt","w",stdout);
	int t;cin >> t;
	for(int i=1;i<=t;i++){
		cout << "Case" << ' ' << i << ':' << ' ';
		memset(cnt,0,sizeof cnt);
		memset(pre,0,sizeof pre);
		memset(dp,inf,sizeof dp);
		int n,m;cin >> n >> m;
		for(int j=0;j<n;j++){
			int a; cin >> a;
			a--;
			for(int r=0;r<m;r++){
				cnt[a][r]+=pre[r];//使a在r颜色之前需要换多少次
				//每次加入一个数字就更新前面
			}
			pre[a]++;
		}
		for(int j=0;j<m;j++)
			for(int r=0;r<m;r++)cout << cnt[j][r] << endl;
		dp[0]=0;
		int s = 1<<m;
		for(int j=0;j<s;j++)//0表示乱序
			for(int r=0;r<m;r++){//r乱序,将所有乱序的都放到一旁
				if(j>>r & 1)continue;//如果不是1continue	
				long long cost=0;
				for(int k=0;k<m;k++){
					if(k==r || j>>k & 1)continue;
					cost += cnt[r][k];
				}
				dp[j | 1<<r]=min(dp[j | 1 << r],dp[j]+cost);
			}
		cout << dp[s-1] << '\n';
	}
	
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值