116. 飞行员兄弟

题目链接

116. 飞行员兄弟

“飞行员兄弟”这个游戏,需要玩家顺利的打开一个拥有 \(16\) 个把手的冰箱。

已知每个把手可以处于以下两种状态之一:打开或关闭。

只有当所有把手都打开时,冰箱才会打开。

把手可以表示为一个 \(4×4\) 的矩阵,您可以改变任何一个位置 \([i,j]\) 上把手的状态。

但是,这也会使得第 \(i\) 行和第 \(j\) 列上的所有把手的状态也随着改变。

请你求出打开冰箱所需的切换把手的次数最小值是多少。

输入格式

输入一共包含四行,每行包含四个把手的初始状态。

符号 \(+\) 表示把手处于闭合状态,而符号 \(-\) 表示把手处于打开状态。

至少一个手柄的初始状态是关闭的。

输出格式

第一行输出一个整数 \(N\),表示所需的最小切换把手次数。

接下来 \(N\) 行描述切换顺序,每行输出两个整数,代表被切换状态的把手的行号和列号,数字之间用空格隔开。

注意:如果存在多种打开冰箱的方式,则按照优先级整体从上到下,同行从左到右打开。

数据范围

\(1≤i,j≤4\)

输入样例:

-+--
----
----
-+--

输出样例:

6
1 1
1 3
1 4
4 1
4 3
4 4

解题思路

dfs

开关问题:每个位置只操作一次

数据量比较小,由此想到直接暴搜,注意这里跟普通的开关问题不同,不用用递推求解

  • 时间复杂度:\(O(16\times 2^{16})\)

代码

// Problem: 飞行员兄弟
// Contest: AcWing
// URL: https://www.acwing.com/problem/content/118/
// Memory Limit: 64 MB
// Time Limit: 1000 ms
// 
// Powered by CP Editor (https://cpeditor.org)

// %%%Skyqwq
#include <bits/stdc++.h>
 
//#define int long long
#define help {cin.tie(NULL); cout.tie(NULL);}
#define pb push_back
#define fi first
#define se second
#define mkp make_pair
using namespace std;
 
typedef long long LL;
typedef pair<int, int> PII;
typedef pair<LL, LL> PLL;
 
template <typename T> bool chkMax(T &x, T y) { return (y > x) ? x = y, 1 : 0; }
template <typename T> bool chkMin(T &x, T y) { return (y < x) ? x = y, 1 : 0; }
 
template <typename T> void inline read(T &x) {
    int f = 1; x = 0; char s = getchar();
    while (s < '0' || s > '9') { if (s == '-') f = -1; s = getchar(); }
    while (s <= '9' && s >= '0') x = x * 10 + (s ^ 48), s = getchar();
    x *= f;
}

char g[7][7];
vector<PII> res,bk;
bool ck()
{
	bool f=true;
	for(int i=1;i<=4;i++)
		for(int j=1;j<=4;j++)
			if(g[i][j]=='+')f=false;
	return f;
}
void turn(int x,int y)
{
	for(int i=1;i<=4;i++)
	{
		if(g[x][i]=='-')g[x][i]='+';
		else
			g[x][i]='-';
		if(i!=x)
		{
			if(g[i][y]=='-')g[i][y]='+';
			else
				g[i][y]='-';
		}
	}
}
void dfs(int x,int y)
{
	if(y==5)y=1,x++;
	if(x>4)
	{
		if(ck())
		{
			if(!res.size()||bk.size()<res.size())
				res=bk;
		}
		return ;
	}
	bk.pb({x,y});
	turn(x,y);
	dfs(x,y+1);
	bk.pop_back();
	turn(x,y);
	dfs(x,y+1);
}
int main()
{
    for(int i=1;i<=4;i++)cin>>(g[i]+1);
    dfs(1,1);
    cout<<res.size()<<'\n';
    for(auto r:res)cout<<r.fi<<' '<<r.se<<'\n';
    
    return 0;
}
posted @ 2022-02-23 11:34  zyy2001  阅读(36)  评论(0编辑  收藏  举报