(1009) HDU 6446 Tree and Permutation(规律+树上各个点的距离和)
2024-09-28 08:55:38
题意:
给一棵N个点的树,对应于一个长为N的全排列,对于排列的每个相邻数字a和b,他们的贡献是对应树上顶点a和b的路径长,求所有排列的贡献和。
分析:
经过简单的分析可以得知,全部的贡献其实相当与(这颗树上各个点的距离之和)*jichen(n-1) *2;
不相信可以举个简单的例子,或者用计算机打表可以知道;
那么如何求树上各个点的距离和呢?
可以参考这个博客:https://www.cnblogs.com/shuaihui520/p/9537214.html ;
那下面的问题就相当的简单了;
#include<bits/stdc++.h>
using namespace std;
const int maxn = ;
const int mod = 1e9+;
#define ll long long
ll sum[maxn];
int n;
ll dp[maxn];
struct no
{
int v,w;
}t1,t2;
vector<no>tree[maxn]; void dfs(int cur, int father)
{
sum[cur] = ;
for(int i = ; i < tree[cur].size(); i++)
{
int son = tree[cur][i].v;
ll len = tree[cur][i].w;
if(father == son)
continue;
dfs(son, cur);
sum[cur] = (sum[cur]+sum[son])%mod;
dp[cur] = ((dp[cur]+dp[son])%mod + (n-sum[son])*sum[son]%mod * len%mod)%mod;
}
}
ll jichen(int n)
{
ll sum=; while()
{
if(n==)
break;
sum=(sum*n)%mod;
n--;
}
return sum;
}
int main( )
{
while(scanf("%d",&n)!=EOF)
{
for(int i= ; i<=n ; i++)
tree[i].clear();
memset(sum,,sizeof(sum));
memset(dp,,sizeof(dp));
for(int i = ; i<n- ; i++)
{
int u,v,w;
scanf("%d%d%d",&u,&v,&w);
u--;v--;
tree[u].push_back(no{v,w});
tree[v].push_back(no{u,w});
}
dfs(,-);
printf("%lld\n",(dp[]*jichen(n-))%mod*%mod);
}
return ;
}
最新文章
- Mono下的WCF的Bug?
- C 语言中的指针和内存泄漏
- highcharts联合jquery ajax 后端取数据
- 【Java每日一题】20170111
- django 学习笔记(一)搭建基础环境
- 搭建struct环境
- PHP程序员的技术成长之路规划
- Linux下ftp和ssh详解
- What Kind of Friends Are You? ZOJ 3960
- 【安富莱原创开源应用第3期】花式玩转网络摄像头之VNC远程桌面版本,稳定运行2年不死机
- Intent之跳转总结
- SQL游标在递归是的时候提示 ";游标"; 名称已经存在的问题
- BZOJ 1912 巡逻(算竞进阶习题)
- Codeforces 862D. Mahmoud and Ehab and the binary string 【二分】(交互)
- [LeetCode] 111. Minimum Depth of Binary Tree ☆(二叉树的最小深度)
- CollisionFlags
- Windows API串口编程详解
- 【ROS系列】使用QT编写ROS订阅、发布程序
- 【51nod】1123 X^A Mod B (任意模数的K次剩余)
- python写exploit采集器