1. 程式人生 > >[Poi2014]Hotel

[Poi2014]Hotel

memset wol stream mat poi2014 開始 from 兩個 putchar

Description
有一個樹形結構的賓館,n個房間,n-1條無向邊,每條邊的長度相同,任意兩個房間可以相互到達。吉麗要給他的三個妹子各開(一個)房(間)。三個妹子住的房間要互不相同(否則要打起來了),為了讓吉麗滿意,你需要讓三個房間兩兩距離相同。
有多少種方案能讓吉麗滿意?

Input
第一行一個數n。
接下來n-1行,每行兩個數x,y,表示x和y之間有一條邊相連。

Output
讓吉麗滿意的方案數。

Sample Input
7
1 2
5 7
2 5
2 3
5 6
4 5

Sample Output
5

HINT
n≤5000

這題\(O(n^2)\)即可,但是我TM開始想了個巨麻煩的做法。。。直接設\(f[i][j]\)

表示深度為\(i\)可以湊出的\(j\)元組的個數,枚舉根之後跑3次dfs即可(加強版需要用長鏈剖分+dp,我不會)

/*program from Wolfycz*/
#include<cmath>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define inf 0x7f7f7f7f
using namespace std;
typedef long long ll;
typedef unsigned int ui;
typedef unsigned long long ull;
inline char gc(){
    static char buf[1000000],*p1=buf,*p2=buf;
    return p1==p2&&(p2=(p1=buf)+fread(buf,1,1000000,stdin),p1==p2)?EOF:*p1++;
}
inline int frd(){
    int x=0,f=1;char ch=gc();
    for (;ch<'0'||ch>'9';ch=gc())   if (ch=='-')    f=-1;
    for (;ch>='0'&&ch<='9';ch=gc()) x=(x<<1)+(x<<3)+ch-'0';
    return x*f;
}
inline int read(){
    int x=0,f=1;char ch=getchar();
    for (;ch<'0'||ch>'9';ch=getchar())  if (ch=='-')    f=-1;
    for (;ch>='0'&&ch<='9';ch=getchar())    x=(x<<1)+(x<<3)+ch-'0';
    return x*f;
}
inline void print(int x){
    if (x<0)    putchar('-'),x=-x;
    if (x>9)    print(x/10);
    putchar(x%10+'0');
}
const int N=5e3;
int pre[(N<<1)+10],now[N+10],child[(N<<1)+10];
ll f[N+10][4],Ans;
int n,tot;
void join(int x,int y){pre[++tot]=now[x],now[x]=tot,child[tot]=y;}
void insert(int x,int y){join(x,y),join(y,x);}
void dfs(int x,int fa,int deep,int T){
    f[deep][T]+=f[deep][T-1];
    for (int p=now[x],son=child[p];p;p=pre[p],son=child[p]){
        if (son==fa)    continue;
        dfs(son,x,deep+1,T);
    }
}
void work(int x){
    memset(f,0,sizeof(f));
    for (int i=1;i<=n;i++)  f[i][0]=1;
    for (int p=now[x],son=child[p];p;p=pre[p],son=child[p])
        dfs(son,x,1,3),dfs(son,x,1,2),dfs(son,x,1,1);
    for (int i=1;i<=n;i++)  Ans+=f[i][3];
}
int main(){
    n=read();
    for (int i=1;i<n;i++){
        int x=read(),y=read();
        insert(x,y);
    }
    for (int i=1;i<=n;i++)  work(i);
    printf("%lld\n",Ans);
    return 0;
}

[Poi2014]Hotel