The Elves(拓扑排序+dp)

#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
#pragma warning(disable:4996)
#define MAX(a,b) (a>b?a:b)
#define MIN(a,b) (a
const int maxn = 100000, maxm = 1999005;
long long mod = 1e9 + 7;
typedef long long ll;
int H[maxn], NXT[maxm], E[maxm], eSize, indegree[maxn];
ll a[maxn], b[maxn], dp[maxn];
void add(int u, int v)
{
    eSize++;
    E[eSize] = v;
    NXT[eSize] = H[u];
    H[u] = eSize;
    indegree[v]++;
    dp[v] += a[u];
}
int n, m, T;
int main()
{
    scanf("%d", &T);
    while (T--)
    {
        memset(H, 0, sizeof(H));
        memset(indegree, 0, sizeof(indegree));
        memset(NXT, 0, sizeof(NXT));
        memset(dp, 0, sizeof(dp));
        eSize = 0;
        scanf("%d%d", &n, &m);
        for (int i = 1; i <= n; i++)
        {
            scanf("%d%d", &a[i], &b[i]);
        }
        int u, v;
        for (int i = 1; i <= m; i++)
        {
            scanf("%d%d", &u, &v);
            add(u, v);
        }
        int Q[maxn], l = 0, r = 0;
        for (int i = 1; i <= n; i++)
        {
            if (!indegree[i])
            {
                Q[r++] = i;
            }
        }
        ll ans = 0;
        while (l != r)
        {
            int x = Q[l++];
            for (int i = H[x]; i; i = NXT[i])
            {
                dp[E[i]] = (dp[E[i]] + dp[x]) % mod;
                indegree[E[i]]--;
                if (!indegree[E[i]])
                {
                    Q[r++] = E[i];
                }
            }
        }
        for (int i = 1; i <= n; i++)
        {
            ans = (ans + (dp[i] * b[i]) % mod) % mod;
        }
        cout << ans << '\n';
    }
}

你可能感兴趣的:(图论,拓扑排序,动态规划)