题目链接:http://acm.csu.edu.cn/csuoj/problemset/problem?pid=1804
解法:先将每个点i对应的count(i,j)*bj算出来然后乘ai,累加就是答案,注意这里要类似拓扑排序那样,不过
要倒着做,避免后效性
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int maxn = 100010;
const int mod = 1e9+7;
struct edge{
int v,next;
edge(int v=0,int next=0):v(v),next(next){}
}E[maxn*2];
LL a[maxn], b[maxn], dp[maxn], du[maxn];
int head[maxn], edgecnt;
void init(){
edgecnt=0;
memset(head, -1, sizeof(head));
}
void add(int u, int v){
E[edgecnt].v = v, E[edgecnt].next = head[u], head[u] = edgecnt++;
}
int n, m;
int main()
{
while(scanf("%d%d",&n,&m)!=EOF)
{
init();
memset(dp, 0, sizeof(dp));
memset(du, 0, sizeof(du));
for(int i=1; i<=n; i++) scanf("%lld%lld",&a[i],&b[i]);
for(int i=1; i<=m; i++){
int u,v;
scanf("%d%d", &u,&v);
add(v,u);
du[u]++;
}
queue<int>q;
for(int i=1; i<=n; i++) if(du[i]==0) q.push(i);
while(!q.empty()){
int u=q.front(); q.pop();
for(int i=head[u]; ~i; i=E[i].next){
int v = E[i].v;
dp[v]=(dp[v]+(dp[u]+b[u])%mod)%mod;
if(--du[v]==0) q.push(v);
}
}
LL ans=0;
for(int i=1; i<=n; i++){
ans=(ans+1LL*dp[i]*a[i]%mod)%mod;
}
printf("%lld\n", ans);
}
return 0;
}
还可以直接记忆化搜索
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int maxn = 1e5 + 5;
LL dp[maxn];
LL a[maxn], b[maxn];
const int mod = 1e9 + 7;
struct EDGE
{
int to, next;
EDGE(int to = 0, int next = 0): to(to), next(next) {}
} edge[maxn];
int head[maxn], edgecnt;
void init()
{
memset(dp, -1, sizeof(dp));
memset(head, -1, sizeof(head));
edgecnt = 0;
}
void add(int s, int t)
{
edge[edgecnt] = EDGE(t, head[s]);
head[s] = edgecnt++;
}
LL dfs(int u)
{
if(dp[u] != -1)
return dp[u];
dp[u] = 0;
for(int i = head[u]; ~i; i = edge[i].next)
{
int v = edge[i].to;
dp[u] += b[v] + dfs(v);
dp[u] %= mod;
}
return dp[u];
}
int main()
{
int n, m;
while(~scanf("%d %d", &n, &m))
{
init();
for(int i = 1; i <= n; i++)
scanf("%lld %lld", &a[i], &b[i]);
while(m--)
{
int u, v;
scanf("%d %d", &u, &v);
add(u, v);
}
for(int i = 1; i <= n; i++)
dfs(i);
LL ans = 0;
for(int i = 1; i <= n; i++)
{
ans += a[i] * dp[i];
ans %= mod;
}
printf("%lld\n", ans);
}
return 0;
}