[POI2014]HOT-Hotels
题目描述
There are nnn towns in Byteotia, connected with only n−1n-1n−1 roads.
Each road directly links two towns.
All the roads have the same length and are two way.
It is known that every town can be reached from every other town via a route consisting of one or more (direct-link) roads.
In other words, the road network forms a tree.
Byteasar, the king of Byteotia, wants three luxury hotels erected to attract tourists from all over the world.
The king desires that the hotels be in different towns and at the same distance one from each other.
Help the king out by writing a program that determines the number of possible locations of the hotel triplet in Byteotia.
有一个树形结构,每条边的长度相同,任意两个节点可以相互到达。选3个点。两两距离相等。有多少种方案?
输入输出格式
输入格式:The first line of the standard input contains a single integer nnn (1≤n≤5 0001\le n\le 5\ 0001≤n≤5 000), the number of towns in Byteotia.
The towns are numbered from 111 to nnn.
The Byteotian road network is then described in n−1n-1n−1 lines.
Each line contains two integers aaa and bbb (1≤a≤b≤n1\le a\le b\le n1≤a≤b≤n) , separated by a single space, that indicate there is a direct road between the towns aaa and bbb.
输出格式:The first and only line of the standard output should contain a single integer equal to the number of possible placements of the hotels.
输入输出样例
说明
有一个树形结构,每条边的长度相同,任意两个节点可以相互到达。选3个点。两两距离相等。有多少种方案?
本题数据很小,n^2的可以过
先枚举转折点,在dfs找到深度,f1[i]表示有1个点距离为i的个数,f2[i]表示有2个点距离为i的个数,ans累加
#include<bits/stdc++.h> #define ll long long using namespace std; const int maxn = 5e3+10; int n,size,head[maxn],maxd; ll f1[maxn],f2[maxn],sum[maxn]; struct edge{ int v,nex; }e[maxn<<1]; void adde(int u,int v) { e[size].v=v;e[size].nex=head[u];head[u]=size++; } void dfs(int u,int fa,int dis) { sum[dis]++;maxd=max(maxd,dis); for(int i=head[u];~i;i=e[i].nex ){ int v=e[i].v; if(v==fa) continue; dfs(v,u,dis+1); } } int main() { memset(head,-1,sizeof(head)); scanf("%d",&n); for(int i=1;i<n;i++) { int u,v;scanf("%d%d",&u,&v); adde(u,v);adde(v,u); } ll ans=0; for(int u=1;u<=n;u++) { memset(f1,0,sizeof(f1)); memset(f2,0,sizeof(f2)); for(int i=head[u];~i;i=e[i].nex) { int v=e[i].v; maxd=1; dfs(v,u,1); for(int j=1;j<=maxd;j++) { ans+=f2[j]*sum[j];f2[j]+=f1[j]*sum[j];f1[j]+=sum[j];sum[j]=0; } } } printf("%lld",ans); return 0; }
据说可以优化,但我不知道