[NOI2013]樹的計數

// luogu-judger-enable-o2
/*
考慮將bfs序按層分段, 每分一段就會使深度+1,因此分的段數+1就是深度
因爲每種分段方式至多隻能對應一種dfs序, 因此咱們的目標就是求出可行的bfs序
而後咱們發現, 若是在bfs序中第i個比第i + 1個後出如今dfs序中, 那麼這裏必定分段

而後咱們考慮dfs序對於bfs序的限制, 假設a[i] < a[i + 1]的話,意味着a[i + 1]和a[i]同層或者在下一層

那麼\sum_{i = a[i]} ^ {a[i + 1] - 1} 分層<= 1

這樣的話獲得了一些限制以及肯定位置, 沒有限制的位置由於任意分均可以, 那麼統計0.5答案便可
 


*/
#include<cstdio>
#include<algorithm>
#include<iostream>
#include<cstring>
#include<queue>
#define mmp make_pair
#define ll long long
#define M 200010
using namespace std;
int read() {
    int nm = 0, f = 1;
    char c = getchar();
    for(; !isdigit(c); c = getchar()) if(c == '-') f = -1;
    for(; isdigit(c); c = getchar()) nm = nm * 10 + c - '0';
    return nm * f;
}
double note[M], s[M];
int  t[M], a[M], pos[M], f[M], sta[M], n, tp;
int main() {
    double ans = 1;
    n = read();
    for(int i = 1; i <= n; i++) t[read()] = i;
    for(int i = 1; i <= n; i++) {
        int x = read();
        a[t[x]] = i, pos[i] = t[x];
    }
    note[1] = 1;
    for(int i = 1; i < n; i++) {
        if(pos[i] > pos[i + 1]) note[i] = 1;
        if(note[i] == 1) {
            f[i]++;
            f[i + 1]--;
        }
        s[i] = s[i - 1] + note[i];
    }
    for(int i = 1; i < n; i++) {
        if(a[i] < a[i + 1]) {
            if(s[a[i + 1] - 1] - s[a[i] - 1] > 0) {
                f[a[i]]++;
                f[a[i + 1]]--;
            } else sta[++tp] = a[i];
        }
    }
    for(int i = 1; i <= n; i++) f[i] += f[i - 1];
    for(int i = 1; i <= tp; i++) {
        if(f[sta[i]] == 0) note[sta[i]] = 0.5;
    }
    for(int i = 1; i <= n; i++) ans += note[i];
    printf("%.3lf\n", ans);
    return 0;
}
相關文章
相關標籤/搜索