【codeforces 797D】Broken BST

【题目链接】:http://codeforces.com/contest/797/problem/D

【题意】

给你一个二叉树;
然后问你,对于二叉树中每个节点的权值;
如果尝试用BST的方法去找;
能不能找到这样一个权值的节点;
(只要找到这个权值的节点就好,没有说特定找哪一个)

【题解】

对于二叉树中的每一个节点,我们都能确定;
可以到达这个节点的权值的范围;
对于节点不在这个权值范围内的点;
答案递增;
但有可能会有
3
2 -1 -1
1 1 3
2 -1 -1
这样的数据
这里的答案应该是0而不是1;
因为2是能够通过bst的方法找到的;
虽然找左儿子的时候返回的是右儿子的;但是找到了!
所以最后如果有某些权值在某一些地方找不到,但是在另外一些地方找到了则也是可以的.

【Number Of WA

2

【完整代码】

#include <bits/stdc++.h>
using namespace std;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define LL long long
#define rep1(i,a,b) for (int i = a;i <= b;i++)
#define rep2(i,a,b) for (int i = a;i >= b;i--)
#define mp make_pair
#define pb push_back
#define fi first
#define se second
#define ms(x,y) memset(x,y,sizeof x)

typedef pair<int,int> pii;
typedef pair<LL,LL> pll;

const int dx[9] = {0,1,-1,0,0,-1,-1,1,1};
const int dy[9] = {0,0,0,-1,1,-1,1,-1,1};
const double pi = acos(-1.0);
const int N = 1e5+100;
const int INF = 1e9+1000;

int n,a[N],l[N],r[N],bo[N],root,ans;
int siz[N];
map <int,int> dic1,dic2;

void dfs2(int x,int fa,int mi,int ma)
{
    if (mi<=a[x]&&a[x]<=ma)
    {
        dic1[a[x]] = 1;
    }
    else
    {
        ans++;
        dic2[a[x]]++;
    }
    if (l[x]!=-1) dfs2(l[x],x,mi,min(ma,a[x]));
    if (r[x]!=-1) dfs2(r[x],x,max(mi,a[x]),ma);
}

int main()
{
    //freopen("F:\rush.txt","r",stdin);
    ios::sync_with_stdio(false),cin.tie(0);
    cin >> n;
    rep1(i,1,n)
    {
        cin >> a[i] >> l[i] >> r[i];
        if (l[i]!=-1) bo[l[i]] = true;
        if (r[i]!=-1) bo[r[i]] = true;
    }
    rep1(i,1,n)
        if (!bo[i])
            root = i;
    dfs2(root,0,-INF,INF);
    rep1(i,1,n)
        if (dic1[a[i]] && dic2[a[i]]>0)
        {
            dic1[a[i]]=0;
            ans-=dic2[a[i]];
        }
    cout << ans << endl;
    return 0;
}
原文地址:https://www.cnblogs.com/AWCXV/p/7626402.html