C. Anji's Binary Tree
网站:https://codeforces.com/problemset/problem/1900/C
这里比较容易搞混的就是各个节点的关系,不要用2*n来表示左孩子!!
以及记得添加快读快写
ios::sync_with_stdio(false);
cin.tie(nullptr);
加在int main()里即可
这里还有一个priority_queue的小技巧:结构体内部定义运算符,好像和sort的cmp有不同?
#include<iostream>
#include<vector>
#include<algorithm>
#include<math.h>
#include<sstream>
#include<string>
#include<string.h>
#include<iomanip>
#include<stdlib.h>
#include<map>
#include<queue>
#include<limits.h>
#include<climits>
#include<fstream>
#include<stack>
typedef long long ll;
using namespace std;
struct leet
{
int left, right;
char tar;
leet() { left = 0; right = 0; tar = ' '; }
};
leet node[300100];
struct dat
{
int val, times;
dat(){}
dat(int va, int tim) { val = va; times = tim; }
bool operator<(const dat& dl) const
{
return this->times > dl.times;//※指把小的times放前面
}
};
int main()
{
ios::sync_with_stdio(false);//imp
cin.tie(nullptr);//imp
int t; cin >> t;
for (int ii = 0; ii < t; ii++)
{
//queue<dat>qd;
priority_queue<dat, vector<dat>>qd;//用优先队列让times少的先过,类似dij?(
int n; cin >> n; cin.get();
string s; getline(cin, s);
for (ll i = 1; i <= n; i++)
{
int xx, yy; cin >> xx >> yy;
node[i].tar = s[i - 1];
node[i].left = xx;
node[i].right = yy;
}
qd.push(dat(1, 0));//排入第一个节点
ll mintimes = 0, jd = 1;
bool isend = 0;
while (!isend)//无所谓的,写一个whiletrue也是一样
{
dat temp = qd.top();
qd.pop();
mintimes = temp.times;
jd = temp.val;
if (node[jd].left == 0 and node[jd].right == 0)
{
isend = 1;
break;
}
if (node[jd].tar == 'U')//如果是u那么times一定得加一,然后分别遍历左右
{
if (node[jd].left != 0)qd.push(dat(node[jd].left, mintimes + 1));
if (node[jd].right != 0)qd.push(dat(node[jd].right, mintimes + 1));
}
else if (node[jd].tar == 'L')//本来就是左边那么遍历左节点就不用加一,遍历右节点才需要加一
{
if (node[jd].left != 0)qd.push(dat(node[jd].left, mintimes));
if (node[jd].right != 0)qd.push(dat(node[jd].right, mintimes + 1));
}
else//同上
{
if (node[jd].right != 0)qd.push(dat(node[jd].right, mintimes));
if (node[jd].left != 0)qd.push(dat(node[jd].left, mintimes + 1));
}
}
cout << mintimes << endl;
}
return 0;
}
♥对了,爱你rzbb♥