【拓扑】【宽搜】CSU 1084 有向无环图 (2016湖南省第十二届大学生计算机程序设计竞赛)

题目链接:

  http://acm.csu.edu.cn/OnlineJudge/problem.php?id=1804

题目大意:

  一个有向无环图(DAG),有N个点M条有向边(N,M<=105),每个点有两个值ai,bi(ai,bi<=109),count(i,j)表示从i走到j的方案数。

  求mod 109+7的值。

题目思路:

  【拓扑】【宽搜】

  首先将式子拆开,每个点I走到点J的d[j]一次就加上一次ai,这样一个点被i走到的几次就加上几次ai,相当于count(i,j)*ai,最终只要求Σ(bj*d[j])即可。

  将这张有向无环图按照拓扑序加入队列,这样保证做到第i个点时在它之后不会再被更新答案(也就是说后面不会影响前面的值,这样才能通过前面的值推出后面的)

  每个点I都把点I的后继节点的d加上ai,最终按照上面那样求Σ(bj*d[j])即可。

 1 //
 2 //by coolxxx
 3 //#include<bits/stdc++.h>
 4 #include<iostream>
 5 #include<algorithm>
 6 #include<string>
 7 #include<iomanip>
 8 #include<map>
 9 #include<stack>
10 #include<queue>
11 #include<set>
12 #include<bitset>
13 #include<memory.h>
14 #include<time.h>
15 #include<stdio.h>
16 #include<stdlib.h>
17 #include<string.h>
18 //#include<stdbool.h>
19 #include<math.h>
20 #define min(a,b) ((a)<(b)?(a):(b))
21 #define max(a,b) ((a)>(b)?(a):(b))
22 #define abs(a) ((a)>0?(a):(-(a)))
23 #define lowbit(a) (a&(-a))
24 #define sqr(a) ((a)*(a))
25 #define swap(a,b) ((a)^=(b),(b)^=(a),(a)^=(b))
26 #define mem(a,b) memset(a,b,sizeof(a))
27 #define eps (1e-8)
28 #define J 10000
29 #define mod 1000000007
30 #define MAX 0x7f7f7f7f
31 #define PI 3.14159265358979323
32 #define N 100004
33 using namespace std;
34 typedef long long LL;
35 int cas,cass;
36 int n,m,lll,ans;
37 LL aans;
38 struct xxx
39 {
40     int next,to;
41 }a[N];
42 int last[N],q[N],in[N],aa[N],bb[N];
43 LL d[N];
44 void add(int x,int y)
45 {
46     a[++lll].to=y;
47     a[lll].next=last[x];
48     last[x]=lll;
49 }
50 void tuopu()
51 {
52     int i,l,r=0;
53     for(i=1;i<=n;i++)if(!in[i])q[++r]=i;
54     for(l=1;l<=r && r!=n;l++)
55         for(i=last[q[l]];i;i=a[i].next)
56             if(--in[a[i].to]==0)
57                 q[++r]=a[i].to;
58     for(l=1;l<=n;l++)
59         for(i=last[q[l]];i;i=a[i].next)
60             d[a[i].to]=(d[a[i].to]+d[q[l]]+aa[q[l]])%mod;
61     for(i=1;i<=n;i++)
62         aans=(aans+1LL*d[i]*bb[i])%mod;
63 }
64 int main()
65 {
66     #ifndef ONLINE_JUDGE
67     freopen("1.txt","r",stdin);
68 //    freopen("2.txt","w",stdout);
69     #endif
70     int i,j,k;
71     int x,y,z;
72 //    for(scanf("%d",&cass);cass;cass--)
73 //    for(scanf("%d",&cas),cass=1;cass<=cas;cass++)
74 //    while(~scanf("%s",s+1))
75     while(~scanf("%d",&n))
76     {
77         lll=aans=0;mem(last,0);mem(in,0);mem(d,0);
78         scanf("%d",&m);
79         for(i=1;i<=n;i++)scanf("%d%d",aa+i,bb+i);
80         for(i=1;i<=m;i++)
81         {
82             scanf("%d%d",&x,&y);
83             add(x,y);in[y]++;
84         }
85         tuopu();
86         printf("%lld
",aans);
87     }
88     return 0;
89 }
90 /*
91 //
92 
93 //
94 */
View Code
原文地址:https://www.cnblogs.com/Coolxxx/p/5842631.html