hdu2647Reward

来源:互联网 发布:网络个人信息泄露案例 编辑:程序博客网 时间:2024/06/07 03:36

这个题目是拓扑排序,因为边的数目非常大,所以普通的建图会爆内存,所以这里采用vector容器。

1:建完图后对入度为0的点加入队列,然后对整幅图进行扫描,得到每个点的位置。

2:要用一个数组存相对位置,所以不能只用一个变量存储,因为每次出队列只能有一个元素。。

2:用数组模拟果然比stl快一些。。。

题目链接:

哈哈 我在这里

题面:

Reward

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


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
 

Author
dandelion
 

Source
曾是惊鸿照影来
 

Recommend
yifenfei   |   We have carefully selected several similar problems for you:  1285 1811 2680 2112 2094 
 


代码如下:

#include<cstdio>#include<iostream>#include<vector>#include<cstring>using namespace std;const int maxn=10000+1;int in[maxn],order[maxn],Gery[maxn];int n,m,sum;vector<int>vec[maxn];void read_graph(){    int u,v;    for(int i=0;i<=n;i++)//这个地方有改动    {        in[i]=0;        order[i]=0;        vec[i].clear();    }    for(int i=1;i<=m;i++)    {       scanf("%d%d",&u,&v);       in[u]++;       vec[v].push_back(u);    }}int topo(){     int head=0,tail=0,ans;     sum=n;     for(int i=1;i<=n;i++)     {         if(in[i]==0)            Gery[tail++]=i;     }     while(head<tail)     {         sum--;         int top=Gery[head];         int temp=order[top];         head++;         for(int i=0;i<vec[top].size();i++)         {             if(--in[vec[top][i]]==0)             {                 order[vec[top][i]]=temp+1;                 Gery[tail++]=vec[top][i];             }         }     }     if(sum>0)        return -1;     else     {         ans=888*n;         for(int i=1;i<=n;i++)            ans=ans+order[i];     }      return ans;}int main(){    while(~scanf("%d%d",&n,&m))    {        read_graph();        int ans=topo();        if(ans!=-1)            printf("%d\n",ans);        else            printf("-1\n");    }    return 0;}/*5 42 14 23 15 3*/


0 0
原创粉丝点击