2016湖南省省赛 B 有向无环图(树形dp)

d[u]表示u到其他所有点的路径数*对应点的权值的和

 1 #define bug(x) cout<<#x<<" is "< 2 #define IO std::ios::sync_with_stdio(0)
 3 #include 
 4 #define iter ::iterator
 5 #define pa pair
 6 #define pp pair
 7 using namespace  std;
 8 #define ll long long
 9 #define mk make_pair
10 #define pb push_back
11 #define se second
12 #define fi first
13 #define ls o<<1
14 #define rs o<<1|1
15 const ll mod=1e9+7;
16 const int N=1e5+10;
17 int n,m;
18 vector<int>g[N];
19 ll a[N],b[N],vis[N];
20 ll d[N],in[N];
21 void dfs(int u){
22     if(vis[u])return;
23     vis[u]=1;
24     d[u]=0;
25     for(auto v:g[u]){
26         dfs(v);
27         d[u]=(d[u]+d[v]+b[v])%mod;
28     }
29 }
30 int main(){
31     while(~scanf("%d%d",&n,&m)){
32         for(int i=1;i<=n;i++){
33             g[i].clear();
34             in[i]=0;
35             d[i]=0;
36         }
37         for(int i=1;i<=n;i++){
38             scanf("%lld%lld",&a[i],&b[i]);
39         }
40         for(int i=1;i<=m;i++){
41             int x,y;
42             scanf("%d%d",&x,&y);
43             in[y]++;
44             g[x].pb(y);
45         }
46         for(int i=1;i<=n;i++){
47             if(!in[i])dfs(i);
48         }
49         ll ans=0;
50         for(int i=1;i<=n;i++){
51             ans=(ans+a[i]*d[i]%mod)%mod;
52         }
53         printf("%lld\n",ans);
54     }
55 }

 

你可能感兴趣的:(2016湖南省省赛 B 有向无环图(树形dp))