1 solutions
-
0
T3
考虑一个数对 的贡献,假设 ,可以发现:
- 如果从 的子树开始遍历(必定先经过 ),那么他们吃不到这个逆序对。
- 假设从 中的某个点开始遍历(可以先 也可以先 ),逆序对的期望数是 。
- 假设从 以外的节点开始遍历(必定先经过 的点),逆序对数的期望是 。
于是我们从 开始搜索,如果搜索到 就给 打一个 的标记,再给 本身 (因为 本身吃不到),再给 打一个 的标记,最后下放节点即可,更新节点值即可。
菊花图:u相等怎么使用
先考虑这个题: 的排列的期望逆序对是多少。
答案是 ,因为一组数 ,要么 在 前要么 在 前,他们的贡献是 。
可以发现只有 的位置是固定的(首位),其他的数可以在 dfs 序中 的任何一个位置。
也就是说 这个点的答案是 。
然后考虑其他的点。
我们可以发现点 为根的时候他肯定在 前面,然后其他的数肯定是在 dfs 序中 中的任何一个位置。
也就是说其他点的答案是 。
时间复杂度 。
链:
当 为根的时候我们可以发现 肯定在最前面,但是除此之外,只有 左边的链和 右边的链产生的贡献。
也就是说我们可以有 左边的数 右边的数这么多对贡献为 的(跟菊花图一个道理)。
可以树状数组 正着扫一遍反着扫一遍来实现。
时间复杂度 。
首先考虑以 为根的答案,可以发现,如果 没有祖先关系,贡献是 ;假如 有祖先关系, 是 的祖先,我们可以通过 dfs 统计 的对数,贡献是 ,即 dfs 的时候维护树状数组,设 为 为根的有根树的子树逆序对数。
然后考虑 转移到 ( 的某个孩子),有 对 这棵子树贡献的逆序对数 对除这棵子树贡献的逆序对数。
可以发现,只有这两个节点的 值会改变,其他点都不会改变,因为只有他们变换了父子关系,其他都是兄弟关系。
然后我们发现可以维护 对 这棵子树的逆序对(dfs 序 + 主席树)/线段树合并。
因此我们可以 的从 的答案转移得到 的 值。
#include <bits/stdc++.h> #define rep(i,h,t) for(int i=h;i<=t;i++) #define dep(i,t,h) for (int i=t;i>=h;i--) #define ll long long #define int ll using namespace std; const int N=1e6; int n; vector<int> ve[N]; int cnt=0; #define mid ((h+t)/2) const int mo=1e9+7; ll fsp(int x,int y) { if (y==0) return 1; if (y==1) return x; ll ans=fsp(x,y/2); ans=ans*ans%mo; if (y%2==1) ans=ans*x%mo; return ans; } int siz[N],dfn[N],rt[N],fa[N]; ll p[N]; void dfs(int x,int y) { dfn[x]=++cnt; siz[x]=1; fa[x]=y; for (auto v:ve[x]) if (v!=y) { dfs(v,x); siz[x]+=siz[v]; } } ll ans1=0,ans2=0; ll ans[N]; int inv2; ll P[N]; void dfs3(int x,int y,ll o1,ll o2) { o1%=mo; o2%=mo; ans[x]=((1ll*n*(n+1)/2-o1)%mo*inv2+o2)%mo; for (auto v:ve[x]) if (v!=y) { dfs3(v,x,o1-siz[v]+n-siz[v],o2+v-1-P[v]); } } char ss[1<<26],*A=ss,*B=ss; inline char gc() { return (A==B&&(B=(A=ss)+fread(ss,1,1<<26,stdin),A==B)?EOF:*A++); } template<class T>void read(T &x) { int f=1,c; while (c=gc(),c<48||c>57) if (c=='-') f=-1; x=c^48; while (c=gc(),47<c&&c<58) x=(x<<3)+(x<<1)+(c^48); x*=f; } struct re{ int a,b,c; }; vector<re> Q[N]; struct BIT{ int tr[N]; inline void add(int x,int y){ while(x<=n)tr[x]+=y,x+=x&-x; } inline int q(int x){ int ans=0; while(x)ans+=tr[x],x-=x&-x; return ans; } inline int query(int l,int r){ return q(r)-q(l-1); } inline void clear(){ memset(tr,0,sizeof(tr)); } }T; inline void solve(){ for(int i=1;i<=n;++i){ T.add(dfn[i],1); for(auto x:Q[i]){ P[x.c]+=T.query(x.a,x.b); } } T.clear(); } signed main() { freopen("permutation.in","r",stdin); freopen("permutation.out","w",stdout); ios::sync_with_stdio(false); int T; inv2=fsp(2,mo-2); read(n); rep(i,1,n-1) { int x,y; read(x); read(y); ve[x].push_back(y); ve[y].push_back(x); } dfs(1,0); rep(i,1,n) ans1+=siz[i]; rep(i,1,n) Q[i-1].push_back((re){dfn[i],dfn[i]+siz[i]-1,0}); rep(i,1,n) { if (fa[i]) Q[fa[i]-1].push_back((re){dfn[i],dfn[i]+siz[i]-1,i}); Q[i-1].push_back((re){dfn[i],dfn[i]+siz[i]-1,i}); } solve(); ans2=P[0]; dfs3(1,0,ans1,ans2); rep(i,1,n) cout<<ans[i]<<"\n"; return 0; }
- 1
Information
- ID
- 64
- Time
- 1000ms
- Memory
- 512MiB
- Difficulty
- 9
- Tags
- (None)
- # Submissions
- 17
- Accepted
- 4
- Uploaded By