L2-012 Juicio sobre el montón (montón simulado + procesamiento de cadena)

enlace de tema

https://pintia.cn/problem-sets/994805046380707840/problems/994805064676261888

ideas

Primero implementamos el montón simulando (aquí solo necesitamos implementar la inserción del montón), y luego para cuatro casos:

  • x es el nodo raíz, solo necesitamos determinar si el primer elemento en el montón es x
  • x es el nodo padre de y, solo necesitamos juzgar y >> 1 y >> 1y>>es 1 igual axxx porque el nodo raíz comienza desde 1, lo mismo es cierto a continuación
  • x es un nodo hijo de y, solo necesitamos juzgar x >> 1 x >> 1X>>es 1 igual ayyy
  • x e y son hermanos, solo tenemos que juzgar ( x > > 1 ) == ( y > > 1 ) (x>>1) == (y>>1)( X>>1 )==(y>>1 )

Tenga en cuenta que es muy posible pensar demasiado aquí, por ejemplo, si el nodo secundario se considera un nodo nieto (no se cuenta aquí), si el nodo hermano es un medio hermano (tampoco se cuenta aquí), y luego es incorrecto Para más detalles, por favor vea el código

código

#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define mod 1000000009
#define endl "\n"
#define PII pair<int,int>

const int N = 2e6+10;
int n,m,cnt,h[N],hp[N],ph[N];
int k,x,kk=0;
//ph记录的是第i次存入的下标
//hp记录的是下标为i是第几次存入的
//ph和hp是一个互逆的数组

void heap_swap(int a,int b){
    
    //a、b都是下标
	swap(ph[hp[a]],ph[hp[b]]);
	swap(hp[a],hp[b]);
	swap(h[a],h[b]);
}
void up(int u) {
    
    //向上更新
	while((u>>1) && h[u] < h[u>>1]) {
    
    
		heap_swap(u,u >> 1);
		u >>= 1;
	}
}
void insert(int k){
    
    
	cnt++;
	kk++;//表示是第kk次插入的
	h[cnt] = k;
	ph[kk] = cnt,hp[cnt] = kk;
	up(cnt);
}

map<int,int> st;

int main()
{
    
    
	ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
	string op;
	cin>>n>>m;
	
	for(int i = 1;i <= n; ++i){
    
    
		cin>>k;
		insert(k);
	} 
	for(int i = 1;i <= n; ++i)
		st[h[i]] = i;
	
	while(m--){
    
    
		string op;
		int x,y;
		cin>>x>>op;
		bool ans;
		if(op == "is"){
    
    
			cin>>op;
			if(op == "the") {
    
    
				cin>>op;
				if(op == "root") {
    
    //x是根结点
					if(h[1] == x) ans = true;
					else ans = false;
				} else {
    
    //x是y的父结点
					cin>>op>>y;
					x = st[x],y = st[y];
					if(x < y && (y>>1 == x)) ans = true;
					else ans = false;
				}
			} else {
    
    //x是y的一个子结点
				cin>>op>>op>>y;
				x = st[x],y = st[y];
				if(x > y && (x>>1 == y)) ans = true;
				else ans = false;
			}
		} else {
    
    //x和y是兄弟结点
			cin>>y;
			getline(cin,op);
			x = st[x],y = st[y];
			if((x>>1) == (y>>1)) ans = true;
			else ans = false;
		}
		if(ans) cout<<"T"<<endl;
		else cout<<"F"<<endl;
	}
	
	
	return 0;
}

Supongo que te gusta

Origin blog.csdn.net/m0_46201544/article/details/123830182
Recomendado
Clasificación