洛谷 P2210 Haywire 题解

题目传送门

题目大意: n n n 个人,每个人恰好有 3 3 3 个朋友,将 n n n 个人排成一列,代价为所有朋友之间的距离之和,求出最小代价的排列方式。

题解

一开始看到 n ≤ 12 n\leq 12 n12 以为是什么奇怪的深搜,膜拜一发题解之后发现是模拟退火……

每次退火考虑交换任意两个人的位置,然后求出新代价和原代价比较一下即可。

代码如下:

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <algorithm>
#include <cmath>
using namespace std;
#define delta 0.99
#define maxn 20

int n,a[maxn][3],ans=999999999;
int b[maxn]={0,6, 5, 1, 4, 2, 3},c[maxn];
int work()//求出代价
{
	int re=0;
	for(int i=1;i<=n;i++)c[b[i]]=i;
	for(int i=1;i<=n;i++)
	for(int j=0;j<=2;j++)re+=abs(i-c[a[b[i]][j]]);
	return re/2;
}
void fire()
{
	double T=10000000.0;//初始温度
	for(int i=1;i<=n;i++)b[i]=0;
	for(int i=n;i>=1;i--)//随机一个初始序列
	{
		int pos=rand()%i+1;
		for(int j=1;j<=n;j++)
		if(!b[j]){pos--;if(!pos){b[j]=i;break;}}
	}
	int value=work();
	while(T>1e-10)
	{
		int x=rand()%n+1,y=rand()%n+1;
		while(x==y)y=rand()%n+1;
		swap(b[x],b[y]);
		int new_val=work();
		if(new_val<value||(exp(1.0*(value-new_val)/T)>1.0*rand()/RAND_MAX))value=new_val;
		else swap(b[x],b[y]);
		T*=delta;
		if(value<ans)ans=value;
	}
}

int main()
{
	scanf("%d",&n);srand(9904);
	for(int i=1;i<=n;i++)scanf("%d %d %d",&a[i][0],&a[i][1],&a[i][2]);
	fire();fire();fire();fire();
	printf("%d",ans);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值