大意:Dandelion's uncle的工厂开始分红,厂里的工人们有些有特殊的要求,如A工人的工资一定要大于B,B工人的工资一定要大于C,而不能出现A > B,B> C,C > A的情况。

 

思路:拓扑排序。(基于邻接表BFS拓扑排序,邻接矩阵会MLE)。

 

CODE:

 

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <queue>
using namespace std;

const int M = 10005;
int u[4*M], v[4*M], next[4*M], w[4*M], topo[4*M];
int first[M], d[M];
int ind[M], money[M];
int n, m, cnt, tot;


void init()
{
    cnt = tot = 0;
    memset(ind, 0sizeof(ind));
    memset(first, -1sizeof(first));
    memset(topo, 0sizeof(topo));
    for(int i = 1; i <= n; i++) money[i] = 888;
}

void read_graph(int u1, int v1)
{
    v[cnt] = v1; next[cnt] = first[u1]; first[u1] = cnt++;
}

int toposort()
{
    queue<int> q;
    int ans = 0;
    for(int i = 1; i <= n; i++) if(!ind[i])
        q.push(i);
    while(!q.empty())
    {
        int x = q.front(); q.pop();
        topo[++tot] = x;
        ans += money[x];
        for(int e = first[x]; e!=-1; e = next[e])
        {
            if(--ind[v[e]] == 0)
            {
                money[v[e]] = money[x]+1;
                q.push(v[e]);
            }
        }
    }
    if(tot != n) return -1;
        return ans;
}

int main()
{
    while(~scanf("%d%d", &n, &m))
    {
        init();
        while(m--)
        {
            int u1, v1;
            scanf("%d%d", &u1, &v1);
            read_graph(v1, u1);     //反向处理边,从而好求最小金钱。
            ind[u1]++;
        }
        int ans = toposort();
        if(ans != -1)
        {
            printf("%d\n", ans);
        }
        else printf("-1\n");
    }
    return 0;
}

 

posted on 2012-09-18 21:25  有间博客  阅读(261)  评论(0编辑  收藏  举报