一道蛮简单的题目,就堆排序中向上调整然后字符串处理即可,由于很少练习过string库,所以在模拟练习中吃瘪了
字符串的处理
//建立索引表
string s = "is the root and are siblings parent of left right child";//用来筛选数字
string s1 = "siblings root parent left right";//用来筛选关系
//字符串切片
for (int j = 0; j < strTemp.length(); j++) {
if (strTemp[j] == ' ') {
if (s.find(str) == string::npos) v.push_back(str);
if (s1.find(str) != string::npos) str2 = str;
str.clear();
} else str += strTemp[j];
}
整道题的求解
#include <iostream>
#include <set>
#include <algorithm>
#include <vector>
using namespace std;
const int maxn1 = 1010, maxn2 = 25,maxn3 = 20010;
int heap[maxn1],HashTable[maxn3];
string s = "is the root and are siblings parent of left right child";
string s1 = "siblings root parent left right";
void upAdjust(int low,int high)
{
int i = high,j = high / 2;
while(j >= 1)
{
if(heap[j] < heap[i])
{
swap(heap[j],heap[i]);
i = j;
j = i / 2;
}
else break;
}
}
int strToNum(string str)
{
int len = str.length(),ans = 0;
for(int i = 0; i < len; i--)
{
ans = ans * 10 + str[i] - '0';
}
return ans;
}
int main()
{
int N,M;
scanf("%d %d",&N,&M);
for(int i = 1; i <= N; i++)
{
scanf("%d",&heap[i]);
upAdjust(1,i);
}
for(int i = 1;i <= N; i++) HashTable[10000+heap[i]] = i;
string strTemp;
getchar();
for(int i = 1; i <= M; i++)
{
printf("[0] %d\n",i);
getline(cin, strTemp);
strTemp += ' ';
string str, str2;
vector<string> v;
int strNum = 0;
for (int j = 0; j < strTemp.length(); j++) {
if (strTemp[j] == ' ') {
if (s.find(str) == string::npos) v.push_back(str);
if (s1.find(str) != string::npos) str2 = str;
str.clear();
} else str += strTemp[j];
}
cout<<str2<<endl;
if(str2 == "root")
{
int x = strToNum(v[0]);
if(HashTable[10000+x] == 1) printf("1");
else printf("0");
}
if(str2 == "siblings")
{
int x = strToNum(v[0]);
int y = strToNum(v[1]);
int parX = HashTable[10000+x]/2;
int parY = HashTable[10000+y]/2;
if(parX == parY) printf("1");
else printf("0");
}
if(str2 == "parent")
{
int x = strToNum(v[0]);
int y = strToNum(v[1]);
int posX = HashTable[10000+x];
int posY = HashTable[10000+y];
if(posX == (posY/2)) printf("1");
else printf("0");
}
if(str2 == "left")
{
int x = strToNum(v[0]);
int y = strToNum(v[1]);
int posX = HashTable[10000+x];
int posY = HashTable[10000+y];
if(posX * 2 == posY) printf("1");
else printf("0");
}
if(str2 == "right")
{
int x = strToNum(v[0]);
int y = strToNum(v[1]);
int posX = HashTable[10000+x];
int posY = HashTable[10000+y];
if(posX * 2 + 1 == posY) printf("1");
else printf("0");
}
}
}