Bobo 有一个 n 个点,m 条边的有向无环图(即对于任意点 v,不存在从点 v 开始、点 v 结束的路径)。
为了方便,点用 1,2,…,n 编号。 设 count(x,y) 表示点 x 到点 y 不同的路径数量(规定 count(x,x)=0),Bobo 想知道
除以 (10 9+7) 的余数。
其中,a i,b j 是给定的数列。
Input
输入包含不超过 15 组数据。
每组数据的第一行包含两个整数 n,m (1≤n,m≤10 5).
接下来 n 行的第 i 行包含两个整数 a i,b i (0≤a i,b i≤10 9).
最后 m 行的第 i 行包含两个整数 u i,v i,代表一条从点 u i 到 v i 的边 (1≤u i,v i≤n)。
Output
对于每组数据,输出一个整数表示要求的值。
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
思路:
题目说明了是一个有向无环图,很容易想到要用拓扑。
对于每一个节点,后继节点=(后继节点+当前节点+b[当前节点]), 再取模
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <string>
#include <algorithm>
using namespace std;
#define rep(i,a,n) for(int i=a;i<n;i++)
#define mem(a,n) memset(a,n,sizeof(a))
#define pb push_back
#define IO ios::sync_with_stdio(false);
typedef long long ll;
const int N=1e5+5;
const double eps=1e-4;
const int MOD=1e9+7;
const int dir[4][2]= {-1,0,1,0,0,-1,0,1}; ///上下左右
const int INF=0x3f3f3f3f;
struct Edge
{
int to,next;
Edge() {}
Edge(int to,int next):to(to),next(next) {}
} g[N];
int cnt=0;
int a[N],b[N],head[N];
int in[N];/// 入度
ll num[N]; /// 会爆int
int n,m;
void addedge(int u,int v)
{
cnt++;
g[cnt]=Edge({v,head[u]});
head[u]=cnt;
in[v]++; ///入度+1
}
void init()
{
cnt=0;
mem(head,-1);
mem(in,0);
mem(num,0);
}
void topo()///拓扑排序
{
queue<int>que;
for(int i=1; i<=n; i++)
{
if(!in[i])
{
que.push(i);
}
}
while(!que.empty())
{
int now=que.front();
que.pop();
///printf("now=%d\n",now);
for(int i=head[now]; ~i; i=g[i].next)
{
int to=g[i].to;
///printf("to=%d\n",to);
num[to]=(num[to]+num[now]+b[now])%MOD; /// 注意中间结果会爆int
in[to]--;
if(!in[to]) que.push(to);
}
}
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
init();
for(int i=1; i<=n; i++)
{
scanf("%d%d",&a[i],&b[i]);
}
for(int i=1; i<=m; i++)
{
int u,v;
scanf("%d%d",&u,&v);
addedge(v,u);///反向建图, 反向建图是由于链式前向星的遍历是相反的
}
/*
puts("");
for(int i=1;i<=n;i++)
{
printf("%d %d %d\n",g[i].to,g[i].next,head[i]);
}
puts("");
*/
topo();
ll ans=0;
for(int i=1; i<=n; i++)
{
ans=(ans+1LL*num[i]*a[i])%MOD;
}
printf("%lld\n",ans);
}
return 0;
}