AtCoder ABC周赛2023 12/10 (Sun) D题题解

目录

原题截图:

题目大意:

主要思路:

注:

代码:


原题截图:

题目大意:

给定两个 的矩阵 和 。

你每次可以交换矩阵 的相邻两行中的所有元素或是交换两列中的所有元素。

请问要使 变换至 至少需要几步操作?

如果无法变换至 ,则输出 -1。

主要思路:

这个题正解不好想,但我们看一下数据范围:H,W<=5。我们可以暴力bfs,但我们要枚举有效数组,所以用一个map记录,就做成了。

注:

不要再函数中开数组,用vector<vector<int>>。

代码:

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;
int n,m;
vector<vector<int>> a(10,vector<int>(10)),b(10,vector<int>(10));
bool equation(vector<vector<int>> a,vector<vector<int>> b)
{
	for(int i=1;i<=n;i++)
	{
		for(int j=1;j<=m;j++)
		{
			if(a[i][j]!=b[i][j])
			{
				return 0;
			}
		}
	}
	return 1;
}
struct node{
	vector<vector<int>> x;
	int cnt;
};
map<vector<vector<int>>,bool> mp;
void bfs()
{
	queue<node> q;
	q.push({a,0});
	mp[a] = 1;
	while(!q.empty())
	{
		node tmp=q.front();
		q.pop();
		if(equation(tmp.x,b))
		{
			cout<<tmp.cnt;
			exit(0);
		}
		for(int i=1;i<n;i++)
		{
			swap(tmp.x[i],tmp.x[i+1]);
			if(!mp.count(tmp.x))
			{
				q.push({tmp.x,tmp.cnt+1});
				mp[tmp.x] = 1;	
			}
			swap(tmp.x[i],tmp.x[i+1]);
		}
		for(int i=1;i<m;i++)
		{
			for(int j=1;j<=n;j++)
			{
				swap(tmp.x[j][i],tmp.x[j][i+1]);
			}
			if(!mp.count(tmp.x))
			{
				q.push({tmp.x,tmp.cnt+1});
				mp[tmp.x] = 1;	
			}
			for(int j=1;j<=n;j++)
			{
				swap(tmp.x[j][i],tmp.x[j][i+1]);
			}
		}
	}	
}
int main()
{
	cin>>n>>m;
	for(int i=1;i<=n;i++)
	{
		for(int j=1;j<=m;j++)
		{
			cin>>a[i][j];
		}
	}
	for(int i=1;i<=n;i++)
	{
		for(int j=1;j<=m;j++)
		{
			cin>>b[i][j];
		}
	}
	bfs();
	cout<<-1;
	return 0;
}
相关推荐
倒头就睡的小比特5 天前
算法竞赛C++常用的STL
c++·算法
weilx12345 天前
C++笔记-文件IO-<fcntl.h>
c++
小羊没烦恼!5 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
猎头南楼5 天前
知识社区推荐系统实践:新用户冷启动与长短期兴趣建模的挑战 资深推荐算法工程师
人工智能·深度学习·算法·机器学习
Smileyqp沛沛5 天前
前端?C++ ?较大差异基础罗列
c++·基础·前端转c++
C语言小火车5 天前
C/C++ 为什么需要编译器?
开发语言·c++
旖旎夜光5 天前
力控面试题 01.01: 判定字符是否唯一(位运算) —— 题解
c++·学习·算法·leetcode·力控
wzdark5 天前
大规模并行计算中的负载均衡算法研究4
算法
吞下星星的少年·-·5 天前
C++ 萌新语法入门篇
c++·算法比赛
Because_of_Her15 天前
并查集-听课笔记
笔记·算法·并查集