結果

問題 No.1333 Squared Sum
ユーザー 👑 Nachia
提出日時 2021-01-09 12:32:14
言語 C++17
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 256 ms / 2,000 ms
コード長 1,396 bytes
コンパイル時間 3,016 ms
コンパイル使用メモリ 198,064 KB
最終ジャッジ日時 2025-01-17 15:34:21
ジャッジサーバーID
(参考情報)
judge3 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 44
権限があれば一括ダウンロードができます
コンパイルメッセージ
main.cpp: In function ‘int main()’:
main.cpp:37:8: warning: ignoring return value of ‘int scanf(const char*, ...)’ declared with attribute ‘warn_unused_result’ [-Wunused-result]
   37 |   scanf("%d",&N);
      |   ~~~~~^~~~~~~~~
main.cpp:39:21: warning: ignoring return value of ‘int scanf(const char*, ...)’ declared with attribute ‘warn_unused_result’ [-Wunused-result]
   39 |     int u,v,d; scanf("%d%d%d",&u,&v,&d); u--; v--;
      |                ~~~~~^~~~~~~~~~~~~~~~~~~

ソースコード

diff #

#include<bits/stdc++.h>
using namespace std;
using LL=long long;
using ULL=unsigned long long;
#define rep(i,n) for(int i=0; i<(n); i++)

const ULL M=1000000007;

struct MLL{
	ULL v;
	MLL(ULL a=0){ v=a; }
	void operator+=(MLL r){ v+=r.v; if(v>=M) v-=M; }
	MLL operator+(MLL r) const { r+=*this; return r; }
	void operator*=(MLL r){ v=v*r.v%M; }
	MLL operator*(MLL r) const { r*=*this; return r; }
};

struct Mat{
  MLL S=0,L=0,C=0;
  Mat add_D0() const { return Mat{S,L,C+1}; }
  Mat extend(MLL d) const { return Mat{S+L*2*d+d*d*C,L+C*d,C}; }
};

MLL getSqSum(Mat l,Mat r){ return l.S*r.C + l.L*2*r.L + r.S*l.C; }
Mat operator+(Mat l,Mat r){ return { l.S+r.S, l.L+r.L, l.C+r.C }; }

struct Edge{ int to; MLL d; };

int N;
vector<Edge> E[200000];
Edge P[200000]={};
vector<int> I;
Mat V[200000];
MLL ans=0;

int main(){
  scanf("%d",&N);
  rep(i,N-1){
    int u,v,d; scanf("%d%d%d",&u,&v,&d); u--; v--;
    E[u].push_back({v,ULL(d)});
    E[v].push_back({u,ULL(d)});
  }
  int pI=0;
  P[1]={-1,0}; I.push_back(1);
  while(I.size()>pI){
    int p=I[pI++];
    for(Edge e:E[p]) if(P[p].to!=e.to){ P[e.to]={p,e.d}; I.push_back(e.to); }
  }
  reverse(I.begin(),I.end());
  I.pop_back();

  for(int p:I){
    V[p] = V[p].add_D0();
    V[p] = V[p].extend(P[p].d);
    ans += getSqSum(V[P[p].to],V[p]);
    ans += V[p].S;
    V[P[p].to] = V[P[p].to] + V[p];
  }

  printf("%llu\n",ans.v);

  return 0;
}
0