Topic link: http://acm.csu.edu.cn/csuoj/problemset/problem?pid=1804
Input
Output For each set of data, output an integer representing the required value. Sample Input
3 3 1 1 1 1 1 1 1 2 1 3 2 3 2 2 1 0 0 2 1 2 1 2 2 1 500000000 0 0 500000000 1 2
Sample Output
4 4 250000014
answer:
First, if we calculate $\sum\limits_{i = 1}^n {\sum\limits_{j = 1}^n {\left( {count\left( {i,j} \right) \times a_i \ times b_j } \right)} } $
At this time, if a point i is fixed, and j is enumerated for calculation, there are:
$a_i \times \left[ {\sum\limits_{j = 1}^n {\left( {count\left( {i,j} \right) \times b_j } \right)} } \right]$
我们不妨设$dp\left[ i \right] = \sum\limits_{j = 1}^n {\left( {count\left( {i,j} \right) \times b_j } \right)} $
那么,最后的${\rm{ans}} = \sum\limits_{i = 1}^n {\left\{ {a_i \times \left[ {\sum\limits_{j = 1}^n {\left( {count\left( {i,j} \right) \times b_j } \right)} } \right]} \right\}} $
The question is, what is the state transition equation?
Assuming that for point i, it has K children, we have:
$dp\left[ i \right] = \sum\limits_{k = 1}^K {\left( {b_k + dp\left[ k \right]} \right)} $
(According to the acyclic graph of the title, if there is Edge(i→k), there must be no path from point k to point i, so dp[i] will not be involved when calculating dp[k])
In addition, if this question is not a directed acyclic graph but a tree, it is obvious that dfs can directly calculate the dp[i] of each node i from the root of the tree,
But now for a directed acyclic graph, the following situations may occur:
In this way, if dfs(1) or dfs(2) alone in the main function cannot calculate the dp[i] of all nodes on the entire graph,
Therefore, all nodes i with in-degree[i]==0 should be dfs(i).
AC code:
#include<cstdio> #include<cstring> #include<vector> using namespace std; typedef long long LL; const LL MOD=1e9+7; const int maxn=1e5+10; int n,m; int indegree[maxn]; LL a[maxn],b[maxn]; LL dp[maxn]; struct Edge{ int u,v; Edge(int u,int v){this->u=u,this->v=v;} }; vector<Edge> E; vector<int> G[maxn]; void init(int l,int r) { E.clear(); for(int i=l;i<=r;i++) G[i].clear(); } void addedge(int u,int v) { E.push_back(Edge(u,v)); G[u].push_back(E.size()-1); } LL dfs(int u) { if(dp[u]!=-1) return dp[u]; dp[u]=0; for(int i=0,_size=G[u].size();i<_size;i++) { Edge & e = E [G [u] [i]]; int v = ev; dp[u]=(dp[u]+b[v]+dfs(v))%MOD; } return dp[u]; } intmain () { while(scanf("%d%d",&n,&m)!=EOF) { for(int i=1;i<=n;i++) scanf("%d%d",&a[i],&b[i]); init( 1 ,n); // initialize the adjacency list memset(indegree, 0 , sizeof (indegree)); for ( int i= 1 ,u,v;i<=m;i++ ) { scanf("%d%d",&u,&v); addedge(u,v); index[v] ++ ; } memset(dp,-1,sizeof(dp)); for(int i=1;i<=n;i++) { if(indegree[i]==0) dfs(i); } LL ans=0; for(int i=1;i<=n;i++) ans = ( ans + (dp[i]*a[i]) % MOD ) % MOD; printf("%lld\n",ans); } }