比赛 “Asm.Def战记之太平洋”杯 评测结果 AAAAAATEEE
题目名称 Asm.Def的基本算法 最终得分 60
用户昵称 Binary10 运行时间 1.580 s
代码语言 C++ 内存使用 96.17 MiB
提交时间 2015-11-02 10:34:45
显示代码纯文本
#include<cstdio>
#include<cstring>
#include<vector>
using namespace std;
typedef long long LL;
const int maxn = 5010;
const int MOD = 1e9 + 7;
vector<int> G[maxn];
int w[maxn], p[maxn], d[maxn], lca[maxn][maxn], n;
void dfs(int u, int dep){
  d[u] = dep;
  for(int i = 0; i < G[u].size(); i++)
    dfs(G[u][i], dep + 1);
}
int main()
{
  freopen("asm_algo.in", "r", stdin);
  freopen("asm_algo.out", "w", stdout);
  scanf("%d%d", &n, &w[1]);
  memset(p, -1, sizeof(p));
  for(int i = 2; i <= n; i++){
    scanf("%d%d", &p[i], &w[i]);
    G[p[i]].push_back(i);
  }
  dfs(1, 0);
  for(int i = 1; i <= n; i++)
    for(int j = 1; j <= n; j++){
      int x = i, y = j;
      while(x != y){
        if(d[x] > d[y]) x = p[x];
        else y = p[y];
      }
      lca[i][j] = x;
    }
  int ans = 0;
  for(int i = 1; i <= n; i++)
    for(int j = 1; j <= n; j++)
      ans = (ans + ((LL)w[i] * w[j] % MOD) * (LL)w[lca[i][j]] % MOD) % MOD;
  printf("%d\n", ans);
  return 0;
}