请教一下为什么O2优化这么强?!(~~萌新刚学oi~~)
查看原帖
请教一下为什么O2优化这么强?!(~~萌新刚学oi~~)
285414
Swiftie_wyc22楼主2022/8/30 11:55

我的代码,不开O2,T两个点

开了O2,那两个点只跑200ms就草过去了。

太草了,这啥情况,求大佬解答

#include <bits/stdc++.h>
#define rei register int
#define LL long long
#define IOS ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
#define cvar int n, m, T;
#define rep(i, s, n, c) for (register int i = s; i <= n; i++)
#define CHECK cout<<"WALKED"<<endl;
inline int read(){int x=0,f=1;char ch=getchar();while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();} while(ch>='0' && ch<='9')x=(x<<3)+(x<<1)+ch-'0',ch=getchar();return x*f;}
#define pb push_back
const int INF = INT_MAX;

using namespace std;
int n, m, T;
int mp[7][7];
bool suc;
const int dirx[] = {0,1,1,-1,-1,2,2,-2,-2};// 八个奇怪的方向
const int diry[] = {0,2,-2,2,-2,1,-1,1,-1};
const int final[7][7] = {
	{0,0,0,0,0,0},
	{0,1,1,1,1,1},
	{0,0,1,1,1,1},
	{0,0,0,2,1,1},
	{0,0,0,0,0,1},
	{0,0,0,0,0,0}
}; // white 0, dark 1, empty 2
inline int get_val()
{
	int val = 0;
	for (rei i = 1; i <= 5; i++)
		for (rei j = 1; j <= 5; j++)
			if (mp[i][j] != final[i][j])
				val++;
	// 于是如果越接近结果,价值越小,从而实现优化
	return val;
}
inline bool judge(int x, int y)
{
	if (x < 1 || x > 5 || y < 1 || y > 5)
		return false;
	return true;
}
void ida(int now, int x, int y, int depth)
{
	if (now == depth)
	{
		if (get_val() == 0)
			suc = true;
		return;
	}
	rep(i,1,9,1) // 方向
	{
		int dx = x + dirx[i];
		int dy = y + diry[i];
		if (!judge(dx, dy)) continue;
		swap(mp[x][y], mp[dx][dy]);
		int tv = get_val();
		if (tv + now <= depth) // 判断极限内
			ida(now + 1, dx, dy, depth);
		swap(mp[x][y], mp[dx][dy]); //回溯
	}
}
int main()
{
	T = read();
	while (T--)
	{
		suc = 0; char c;
		int stx, sty;
		for (rei i = 1; i <= 5; i++)
		{
			for (rei j = 1; j <= 5; j++)
			{
				cin >> c;
				if (c == '*')
				{
					mp[i][j] = 2;
					stx =i;
					sty = j;
				}
				else{
					mp[i][j] = c - '0';
				}
			}
		}
		if (!get_val())
		{
			cout << 0 <<endl; continue;
		}
		bool found = false;
		for (rei depth = 1; depth <= 15; depth ++ )
		{
			ida(0,stx,sty, depth);
			if (suc)
			{
				cout << depth <<endl;
				found = true;
				break;
			}
		}
		if (!found)
			cout << - 1 << endl;
	}
	return 0;
}

萌新刚学OI码力不足,借鉴题解请谅解

2022/8/30 11:55
加载中...