跳到正文

题解

P13493题解

#SUSPENDED#约 3 分钟
原文
文章信息与版本

文章信息

发布
2025年7月27日
收录
2025年12月12日
更新
2026年11月9日
篇幅
约 3 分钟
题目
P13493

版本

  1. v1当前

洛谷P13493题解

题目传送门

主要思路

很多人说这道题是状压dp,但是本蒟蒻显然不会,但赛时太保守,觉得dfs会TLE(实际上根本不会,还跑得飞快)。那又该如何是好?那就只能选择模拟退火了。

算法简介

不懂模拟退火的戳这里
模拟退火主要思想就是迭代,答案与初始值无关,非常适宜这道题

代码

码风新奇,不喜勿喷

C++
#include<bits/stdc++.h>
#define int long long
using namespace std;
int n,m;
int a[24][24];
int p[24],b[24];
int cnt,ans,res,js;
void check(int x){//模拟退火函数 
	for(int i=1;i<=n;i++){//判断有无重复,若有则输出-1 
	  ans=0;
	  if(i==x)
	    continue ;
	  for(int j=1;j<=m;j++)
	    if(a[x][j]!=a[i][j])
		  ans=1;
	  if(!ans){
		cout<<-1<<' ';
		return ;
	  }
	}
	cnt=0;//模拟退火的温度 
	ans=1e18;
	while(cnt<=1000){//模拟退火的边界,数据较水,1000就行了 
	  memset(p,0,sizeof p);
	  p[0]=1;
	  random_shuffle(b,b+m);//生成随机数种子,打乱b数组 
	  cnt++;
	  res=0;
	  js=n-1;
	  p[x]=1;
	  int y=0;
	  while(js){//模拟退火主要程序 
		while(p[y]!=0)
		  y=rand()%n+1;
		for(int i=1;i<=n;i++)
		  if(a[i][b[res]]!=a[x][b[res]]&&p[i]==0)
		    js--,p[i]=1; 
		res++;
	  }
	  ans=min(ans,res);
	}
	cout<<ans<<' ';
}
signed main(){
	scanf("%lld%lld",&n,&m);
	for(int i=1;i<=n;i++)
	  for(int j=1;j<=m;j++)
	    scanf("%lld",&a[i][j]);
	for(int i=0;i<m;i++)
	  b[i]=i+1;//预处理b数组 
	if(n==1)
	  cout<<0;
	else
	  for(int i=1;i<=n;i++)
		check(i);
}

管理员大大求过

原文