跳到正文

题解

题解 CF1238E 【Keyboard Purchase】

Ynoi约 5 分钟
原文
文章信息与版本

文章信息

发布
2019年10月9日
收录
2026年8月19日
更新
2026年8月19日
篇幅
约 5 分钟
获赞
7
题目
CF1238E

版本

  1. v1当前

这里是模拟退火做法

不保证每次代码提交都正确

我们先处理出来任意两个字母之间需要移动的次数

这样对于任意一种排列就可以O(m2)O(m^2)的时间算出需要移动的距离

然后我们使用模拟退火

模拟退火就不详细说了,一个较高的初温,较高概率接受较差的解,然后不断降低温度,较低概率接受较差的解。

C++
#include<bits/stdc++.h>
using namespace std;
 
#define MAXN 100005
#define MAXM 22
#define db double 
 
char s[MAXN];
int n,m;
int a[MAXM][MAXM];
int f[1<<20];
int c[MAXN];
 
void rd()
{
	cin >> n >> m;;
	scanf("%s",s+1);
	for(int i = 1; i < n; i ++) 
		a[s[i]-'a'+1][s[i+1]-'a'+1] ++;
}
 
db sj() {
	return ((db)(rand()*rand()%19260817))/(db)19260817;
}
 
int an = 0x3f3f3f3f;
 
int get()
{
	int ans = 0;
	for(int i = 1; i <= m; i ++)
		for(int j = 1; j <= m; j ++)
			ans += abs(c[i]-c[j])*a[i][j];
	if(ans < an) an = ans;
	return ans;
}
 
db mnth(db t,db dt,db tt)
{
	int an = 0;
	for(;t >= tt; t = t*dt)
	{
		int x = rand()%m+1,y = rand()%m+1;
		int ls = get();	
		swap(c[x],c[y]);
		int ans = get();
		if(ans < ls || exp((db)(ans - ls)/t) < sj()*10)
			;
		else
			swap(c[x],c[y]); 		 
	}
	for(int i = 1; i <= 2333; i ++)
	{
		int x = rand()%m+1,y = rand()%m+1;
		int ls = get();	
		swap(c[x],c[y]);
		int ans = get();
		if(ans < ls)
			;
		else
			swap(c[x],c[y]); 
	} 
} 
 
 
signed main()
{
	srand(time(0));
	rd();
	for(int i = 1; i <= m; i ++)
		c[i] = i;
	mnth(100000000,0.9997,0.000001);
	cout<<an;
	return 0;
}

这是我比赛时写的代码,然后竟然神奇的过了pretest

后来我自己去hack了自己=-=

随机一组极限数据就叉掉了。。。

所以说,还是要调调参的

过了pretest之后我怕fst去调参,增大delta,多次退火的方式但是都WA on test 4 可见第一次提交的时候rp有多好=-=

这是我现在的代码,极限随机数据本地大概对拍20几组才会挂=-=

C++
#include<bits/stdc++.h>
using namespace std;

#define MAXN 100005
#define MAXM 22
#define db double 

char s[MAXN];
int n,m;
int a[MAXM][MAXM];
int f[1<<20];
int c[MAXN];

void rd()
{
	cin >> n >> m;;
	scanf("%s",s+1);
	for(int i = 1; i < n; i ++) 
		a[s[i]-'a'+1][s[i+1]-'a'+1] ++;
}

db sj() {
	return ((db)(rand()*rand()%19260817))/(db)19260817;
}

int an = 0x3f3f3f3f;

int get()
{
	int ans = 0;
	for(int i = 1; i <= m; i ++)
		for(int j = 1; j <= m; j ++)
			ans += abs(c[i]-c[j])*a[i][j];
	if(ans < an) an = ans;
	return ans;
}

void mnth(db t,db dt,db tt)
{
	int an = 0;
	for(;t >= tt; t = t*dt)
	{
		int x = rand()%m+1,y = rand()%m+1;
		int ls = get();	
		swap(c[x],c[y]);
		int ans = get();
		if(ans < ls || exp((db)(ans - ls)/t) < sj()*10)
			;
		else
			swap(c[x],c[y]); 		 
	}
	for(int i = 1; i <= 23333; i ++)
	{
		int x = rand()%m+1,y = rand()%m+1;
		int ls = get();	
		swap(c[x],c[y]);
		int ans = get();
		if(ans < ls)
			;
		else
			swap(c[x],c[y]); 
	} 
} 

signed main()
{
	srand(time(0));
	rd();
	for(int i = 1; i <= m; i ++)
		c[i] = i;
	mnth(10000,0.9997,0.0000001);
	mnth(10000,0.9997,0.0000001);
	mnth(100000,0.9997,0.0000001);
	mnth(100000,0.9998,0.0000001);
	mnth(100000,0.9998,0.0000001);
	mnth(100000,0.9999,0.0000001);
	
	cout<<an;	
	return 0;
}
原文
存档评论6 条抓取于