天梯赛 L2-012 关于堆的判断
用数组模拟堆,其中需要注意的就是up函数的写法,
还有从字符串中读入数据,如:sscanf( s.c_str() , "%d is the root" , &x);
#include <bits/stdc++.h>
using namespace std;
#define endl '\n'
// #define int long long
typedef long long ll;
const int N = 50000;
int tree[N],idx = 1;
//建小根堆
void up(int x){
if(x == 1) return;
else{
if(tree[x/2] > tree[x]){ //父亲比我大
swap(tree[x/2],tree[x]);
up(x/2);
}
}
return;
}
void solve() {
int n,m;
cin>>n>>m;
for(int i = 0 ; i < n ; i++){
int x;
cin>>x;
tree[idx]=x;
up(idx);
idx++;
}
getchar();
while(m--){
string s;
getline(cin,s);
int x,y;
if(s.find("root") != string::npos){
//从字符串中读入数字
sscanf(s.c_str(),"%d is the root",&x);
int i;
for(i = 0 ; i < idx ; i++) if(tree[i] == x) break;
if(i == 1) cout<<"T"<<endl;
else cout<<"F"<<endl;
}else if(s.find("siblings") != string::npos){
sscanf(s.c_str(),"%d and %d are siblings",&x,&y);
int i,j;
for(i = 0 ; i < idx ; i++) if(tree[i] == x) break;
for(j = 0 ; j < idx ; j++) if(tree[j] == y) break;
if(i/2 == j/2)cout<<"T"<<endl;
else cout<<"F"<<endl;
}else if(s.find("parent") != string::npos){
sscanf(s.c_str(),"%d is the parent of %d",&x,&y);
int i,j;
for(i = 0 ; i < idx ; i++) if(tree[i] == x) break;
for(j = 0 ; j < idx ; j++) if(tree[j] == y) break;
if(i == j/2)cout<<"T"<<endl;
else cout<<"F"<<endl;
}else if(s.find("child") != string::npos){
sscanf(s.c_str(),"%d is a child of %d",&x,&y);
int i,j;
for(i = 0 ; i < idx ; i++) if(tree[i] == x) break;
for(j = 0 ; j < idx ; j++) if(tree[j] == y) break;
if(i/2 == j)cout<<"T"<<endl;
else cout<<"F"<<endl;
}
}
}
int main() {
// ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
int tt = 1;
// cin >> tt;
while (tt--) {
solve();
}
return 0;
}