团体程序设计天梯赛 L2-012 关于堆的判断 (25分)

题目链接:

L2-012 关于堆的判断 (25分)

思路:

先建堆,然后每个询问都可以用一次dfs解决;

代码:

#include<bits/stdc++.h>

using namespace std;

int n, m, tmp, a[1234];
inline void push(int & x) {
	a[++tmp] = x;
	for(int i = tmp; i > 1; i >>= 1) if(a[i >> 1] > a[i]) swap(a[i >> 1], a[i]);	
}
#define l (u << 1)
#define r ((u << 1) + 1)
bool dfs1(int u, int & x, int &y) {   
	if(l > n) return false;
	if((a[l] == x && a[r] == y) || (a[r] == x && a[l] == y)) return true;
	bool res = false;
	if(l <= n) res |= dfs1(l, x, y);
	if(!res && r <= n) res |= dfs1(r, x, y);
	return res;
}
bool dfs2(int u, int & x, int & y) {
	int p = u >> 1;
	if(p && a[p] == x && a[u] == y) return true;
	bool res = false;
	if(l <= n) res |= dfs2(l, x, y);
	if(!res && r <= n) res |= dfs2(r, x, y);
	return res;
}

int main() {
#ifdef MyTest
	freopen("Sakura.txt", "r", stdin);
#endif
	cin >> n >> m;
	for(int i = 0; i < n; i++) { int x; cin >> x; push(x); }
	while(m--) {
		int x, y;
		string s;
		cin >> x >> s;
		if(s == "and") {
			cin >> y >> s >> s;
			puts(dfs1(1, x, y) ? "T" : "F");
			continue;
		}
		cin >> s;
		if(s == "a") {
			cin >> s >> s >> y;
			puts(dfs2(1, y, x) ? "T" : "F");
			continue;	
		}
		cin >> s;
		if(s == "root") { puts(a[1] == x ? "T" : "F"); continue; }
		cin >> s >> y;
		puts(dfs2(1, x, y) ? "T" : "F");
	}
	return 0;
}
posted @ 2020-01-27 21:01  YuhanのBlog  阅读(145)  评论(0编辑  收藏  举报