米哈游笔试题2021-9-12(偏ACM风格)

一. 括号匹配加贪心

#include 

using namespace std;

int main() {
	ios::sync_with_stdio(false);
	cin.tie(0);
	
	int q; cin >> q;
	stack stk;
	while (q -- ) {
		string s; cin >> s;
		int res = 0;
		for (char c: s) {
			if (c == '{') stk.push(0);
			else if (c == '[') stk.push(1);
			else {
				int t = stk.top(); stk.pop();
				if (t == 0 && c == ']' || t == 1 && c == '}') res ++ ;
			}
		}
		cout << res << endl;
	}
	
	return 0;
}

二. 数论找规律数学题

#include 

using namespace std;

int main() {
	ios::sync_with_stdio(false);
	cin.tie(0);
	
	int q; cin >> q;
	while (q -- ) {
		int x; cin >> x;
		x /= 3; // 12 -> 4 (1, 1, 2) (1, 2, 1) ...
		int res = 0;
		for (int i = 1; i <= x - 2; i ++ ) {
			int d = x - i;
			res += d - 1;
		}
		cout << res << endl;
	}
	
	return 0;
}

三. 棋盘BFS题目

#include 

using namespace std;

typedef pair PII;

int g[12][12], a, b, c, d, n = 10, m = 9;
bool st[12][12];
int dx[8] = {-2, -3, -3, -2, 2, 3, 3, 2};
int dy[8] = {-3, -2, 2, 3, 3, 2, -2, -3};

int k1x[8] = {0, -1, -1, 0, 0, 1, 1, 0};
int k1y[8] = {-1, 0, 0, 1, 1, 0, 0, -1};
int k2x[8] = {-1, -2, -2, -1, 1, 2, 2, 1};
int k2y[8] = {-2, -1, 1, 2, 2, 1, -1, -2};

int bfs() {
	queue q;
	q.push({a, b});
	st[a][b] = true;
	int lev = 0;
	while (q.size()) {
		int len = q.size();
		for (int i = 0; i < len; i ++ ) {
			auto& p = q.front(); q.pop();
			int x = p.first, y = p.second;
			if (x == c && y == d)
				return lev;
			for (int j = 0; j < 8; j ++ ) {
				int _a = x + dx[j], _b = y + dy[j];
				int k1a = x + k1x[j], k1b = y + k1y[j];
				int k2a = x + k2x[j], k2b = y + k2y[j];
				if (_a < 0 || _a >= n || _b < 0 || _b >= m ||
				    st[_a][_b] || (k1a == c && k1b == d) || (k2a == c && k2b == d))
						continue;
				q.push({_a, _b});
				st[_a][_b] = true;
			}
		}
		lev ++ ;
	}
	return -1;
}

int main() {
	ios::sync_with_stdio(false);
	cin.tie(0);
	
	cin >> a >> b >> c >> d;
	cout << bfs() << endl;
	
	return 0;
}

你可能感兴趣的:(算法,算法)