周测2023.9.24

D-小杜捕鱼_周赛 (nowcoder.com)

如果使用二分会超时

#include
using namespace std;
const int N = 1e3 + 10;
int n, m, ans;
char a[N][N];
bool check(int x, int aa, int bb)
{
	for(int i = 1; i <= n; i ++)
	{
		for(int j = 1; j <= m; j ++)
		{
			if(a[i][j] == '#')
			{
				if(abs(aa - i) + abs(bb - j) >= x)return false;
			}
		}
	}
	return true;
}
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 ++)
		{
			int l = 0, r = 1e9 + 10;
			while(l + 1 != r)
			{
				int mid = (l + r) >> 1;
				if(check(mid, i, j))r = mid;
				else l = mid;
			}
			ans = max(ans, l);
		}
	}
	cout << ans;
	return 0;
}

故我们可以进行一定的优化

对于每条鱼我们知道,四个顶点就是可以到达的最远的距离

#include 
using namespace std;

const int N = 1e3 + 5, INF = 0x3f3f3f3f, MOD = 1e9 + 7;

#define x first;
#define y second;

typedef long long LL;
typedef pair PII;

int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};

int n, m;
char g[N][N];

int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);
	cin >> n >> m;

	for (int i = 1; i <= n; i ++)
		for (int j = 1; j <= m; j ++)
			cin >> g[i][j];

	int ans = -1;
	for (int i = 1; i <= n; i ++)
		for (int j = 1; j <= m; j ++)
			if (g[i][j] == '#')
			{

				int d1 = i - 1 + j - 1; 			
				int d = d1;
				int d2 = i - 1 + abs(j - m);		
				d = max(d, d2);
				int d3 = abs(i - n) + j - 1;		
				d = max(d, d3);
				int d4 = abs(i - n) + abs(j - m);	
				d = max(d, d4);
				ans = max(ans, d);
				// cout << d1 << ' ' << d2 << ' ' << d3 << ' ' << d4 << endl;
			}

	cout << ans << endl;
	return 0;
}

F-小红的回文串_周赛 (nowcoder.com)

回文串可以对半遍历,如果遍历到的为’?'则看对应的是否为'?',如果是则说明这里可以有26种变化,如果不是则说明只有一种变化就为对应的字母

注:如果字符串是奇数,则特别注意中间的字母如果中间的字母为’?'则又有了26种变化

#include
using namespace std;
const int mod = 1e9 + 7;
string s;
int sum;
int main()
{
	cin >> s;
	int n = s.size();
	for(int i = 0; i < n / 2; i ++)
	{
		if(s[i] == '?' && s[n - i - 1] == '?')sum ++;
		if(s[i] != s[n - i - 1])
		{
			if(s[i] != '?' && s[n - i - 1] != '?')
			{
				cout << 0;
				return 0;
			}
		}
	}
	long long ans = 1;
	if(n & 1 && s[n / 2] == '?')sum ++;
	for(int i = 0; i < sum; i ++)ans = (ans * 26) % mod;
	cout << ans;
	return 0;
}

你可能感兴趣的:(算法,c++,数据结构)