TopCoder SRM 581 Div1 500 TreeUnion

一个环肯定是由两棵树中的边与中间连接的两条边组成的
那么我们就可以用 c [ 0 / 1 ] [ k ] 表示两棵树中长度为 k 的链的数量
最后的期望就是

c [ 0 ] [ i ] × c [ 1 ] [ K 2 i ] × 2 × ( n 2 ) ! n !

#include <bits/stdc++.h>
using namespace std;
const int N=301;
const int M=N<<1;
int n;
int f[2][N][N];
int c[2][N];

template<class T> void checkmin(T &a,const T &b) { if (b<a) a=b; } 
template<class T> void checkmax(T &a,const T &b) { if (b>a) a=b; }

class TreeUnion {
public:
    double expectedCycles( vector <string> tree1, vector <string> tree2, int K ) ;
};

inline void add(int t,int x,int y){
    f[t][x][y]=f[t][y][x]=1;
}

double TreeUnion::expectedCycles(vector <string> tree1, vector <string> tree2, int K) {
    memset(f,0x3f,sizeof f);
    string s;for(int i=0;i<tree1.size();i++) s+=tree1[i];
    stringstream s1;
    s1<<s;
    int x;
    while(s1>>x) add(0,x,++n);
    s="";for(int i=0;i<tree2.size();i++) s+=tree2[i];
    stringstream s2;
    s2<<s;
    for(int i=1;i<=n;i++) s2>>x,add(1,x,i);
    cout<<n<<endl;
    n++;

    K-=2;
    for(int i=0;i<n;i++) f[0][i][i]=f[1][i][i]=0;
    for(int o=0;o<2;o++)
     for(int i=0;i<n;i++)
      for(int j=0;j<n;j++)
       for(int k=0;k<n;k++)
        f[o][j][k]=min(f[o][j][k],f[o][j][i]+f[o][i][k]);
    for(int o=0;o<2;o++)
     for(int i=0;i<n;i++)
      for(int j=i;j<n;j++)
       c[o][f[o][i][j]]++;
    double ans=0;
    for(int i=1;i<K;i++)
     ans+=1LL*c[0][i]*c[1][K-i];
    ans=ans*2/n/(n-1);
    return ans;
}

猜你喜欢

转载自blog.csdn.net/ymzqwq/article/details/82687599