hdu 2647(拓扑排序)

来源:互联网 发布:魔兽九种兵器修改数据 编辑:程序博客网 时间:2024/06/01 19:19

欢迎参加——每周六晚的BestCoder(有米!)

Reward

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 5560    Accepted Submission(s): 1688


Problem Description
Dandelion's uncle is a boss of a factory. As the spring festival is coming , he wants to distribute rewards to his workers. Now he has a trouble about how to distribute the rewards.
The workers will compare their rewards ,and some one may have demands of the distributing of rewards ,just like a's reward should more than b's.Dandelion's unclue wants to fulfill all the demands, of course ,he wants to use the least money.Every work's reward will be at least 888 , because it's a lucky number.
 

Input
One line with two integers n and m ,stands for the number of works and the number of demands .(n<=10000,m<=20000)
then m lines ,each line contains two integers a and b ,stands for a's reward should be more than b's.
 

Output
For every case ,print the least money dandelion 's uncle needs to distribute .If it's impossible to fulfill all the works' demands ,print -1.
 

Sample Input
2 11 22 21 22 1
 

Sample Output
1777-1


借鉴http://www.cnblogs.com/wally/archive/2013/06/06/3122746.html

空间不够使用邻接矩阵情况下,用vector使用邻接表实现。

#include<iostream>#include<cstdio>#include<cstring>#include<algorithm>#include<queue>#include<vector>using namespace std;#define MAXN 10010typedef pair<int,int>Pair;vector<int>map[MAXN];struct Point {    int id;} point[MAXN];int from[MAXN];int n,m,ans,cnt;bool Solve() {    queue<Pair>Q;    cnt=0;    for(int i=1; i<=n; i++) {        if(from[i]==0) {            Q.push(make_pair(i,0));//找到入度为0的点作为基准            cnt++;//记录入度为0的点的个数        }    }    while(!Q.empty()) {        Pair pp=Q.front();        Q.pop();        int u=pp.first,id=pp.second;//u为头,向各点延伸        for(int i=0; i<map[u].size(); i++) {            int v=map[u][i];            point[v].id=max(id+1,point[v].id);//取最高层数,防止冲突            from[v]--;            if(from[v]==0) {                Q.push(make_pair(v,point[v].id));//将之前入度为0的点及其相关边清楚,进入下一层,加入点v与v的层数                cnt++;//清除点的个数            }        }    }    if(cnt==n)return true;    return false;}int main() {    int u,v;    while(~scanf("%d%d",&n,&m)) {        for(int i=1; i<=n; i++) {            point[i].id=0;            map[i].clear();        }        memset(from,0,sizeof(from));        while(m--) {            scanf("%d%d",&u,&v);            map[v].push_back(u);//邻接表构造            from[u]++;//邻接点个数        }        if(Solve()) {            ans=0;            for(int i=1; i<=n; i++)ans+=point[i].id;            ans+=888*n;            printf("%d\n",ans);        } else            puts("-1");    }    return 0;}


0 0
原创粉丝点击