返回顶部
大江东去,浪淘尽,千古风流人物。故垒西边,人道是,三国周郎赤壁。乱石穿空,惊涛拍岸,卷起千堆雪。江山如画,一时多少豪杰。遥想公瑾当年,小乔初嫁了,雄姿英发。羽扇纶巾,谈笑间,樯橹灰飞烟灭。故国神游,多情应笑我,早生华发。人生如梦,一尊还酹江月。

[POI2014]HOT-Hotels

题目描述

There are nnn towns in Byteotia, connected with only n−1n-1n1 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\ 0001n5 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-1n1 lines.

Each line contains two integers aaa and bbb (1≤a≤b≤n1\le a\le b\le n1abn) , 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.

输入输出样例

输入样例#1: 复制
7
1 2
5 7
2 5
2 3
5 6
4 5
输出样例#1: 复制
5

说明

有一个树形结构,每条边的长度相同,任意两个节点可以相互到达。选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;
    
} 
View Code

据说可以优化,但我不知道

posted @ 2019-05-24 16:59  plysc  阅读(121)  评论(0编辑  收藏  举报