现在的位置: 首页 > 综合 > 正文

Reward——前向星,拓扑排序

2014年10月30日 ⁄ 综合 ⁄ 共 1847字 ⁄ 字号 评论关闭
Reward

Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d
& %I64u

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 1 1 2 2 2 1 2 2 1
 

Sample Output

1777 -1
 

10000 * 10000的数组啊,累死你也开不出来,别做梦了,换个思路吧。。。。。。

前向星,今天刚刚学的,直接用啦,具体是什么,就要看下篇博客啦

<pre name="code" class="html">#include <stdio.h>
#include <string.h>


int head[10009];
struct node
{
    int zd;
    int next;
};
struct node xing[40000];
int rd[10009];
struct no
{
    int zhi;
    int mon;
};
struct no dis[10009];

void tuop(int n)
{
    int i,j,k,low = 0,top = 0;
    int sum = 0,num = 888,ren = 0;
    for(i = 1; i <= n; i++)
    {
        if(rd[i] == 0)
        {
            dis[top].zhi = i;
            dis[top++].mon = num;
        }
    }
    if(top == 0)
    {
        printf("-1\n");
        return ;
    }
    while(low < top)
    {
        k = dis[low].zhi;
        sum += dis[low].mon;
        ren++;
        j = head[k];
        while(1)
        {
            rd[xing[j].zd]--;
            if(rd[xing[j].zd] == 0)
            {
                dis[top].zhi = xing[j].zd;
                dis[top++].mon = dis[low].mon + 1;
            }
            if(j == -1)
                break;
            j = xing[j].next;
        }
        low++;
    }
    if(ren == n)
        printf("%d\n",sum);
    else
        printf("-1\n");
}

int main()
{
    int n,m,coun,a,b;
    int i,j,k;
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        memset(head,-1,sizeof(head));
        memset(rd,0,sizeof(rd));
        coun = 0;
        for(i = 0; i < m; i++)
        {
            scanf("%d%d",&a,&b);
            j = head[b];
            while(j!=-1)
            {
                if(xing[j].zd == a)
                    break;
                else
                    j = xing[j].next;
            }
            if(j==-1)
            {
                rd[a]++;
                xing[coun].zd = a;
                xing[coun].next = head[b];
                head[b] = coun++;
            }
        }
        tuop(n);
    }
    return 0;
}

抱歉!评论已关闭.