天天看點

hdu 2647 拓撲排序變形

Reward

TimeLimit: 2000/1000 MS (Java/Others)    Memory Limit:32768/32768 K (Java/Others)

Total Submission(s): 6976    Accepted Submission(s): 2163

Problem Description

Dandelion's uncle is a boss of afactory. As the spring festival is coming , he wants to distribute rewards tohis 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 thedistributing of rewards ,just like a's reward should more than b's.Dandelion'sunclue wants to fulfill all the demands, of course ,he wants to use the leastmoney.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 rewardshould be more than b's.

Output

For every case ,print the least moneydandelion 's uncle needs to distribute .If it's impossible to fulfill all theworks' demands ,print -1.

Sample Input

21

12

22

12

21

Sample Output

1777

-1

Author

dandelion

Source

曾是驚鴻照影來

 題目大意:給你n個人,m個關系,表示a比b的獎金要多。問最少配置設定的獎金總數是多少。

題目要求的範圍是10000 是以要用鄰接連結清單來做 否則會超記憶體

因為要a的獎金要比b的多 是以 把a看成入度   把b看成出度

還有一個地方需要注意:判斷輸出-1的情況不能隻判斷沒有一個入度為0的點,因為有可能在中間就出現沖突了,如:a——>b——>c——>d——>c有入度為0的點,但卻要輸出-1;

不懂得地方看下面代碼的注釋

AC代碼:

#include<cstdio>

#include <cstring>

#include<queue>

#include<iostream>

#define MAX20005

using namespacestd;

int n,m,a,b;

inthead[MAX],degree[MAX],money[MAX];

struct node

{

    int to;

    int next;

}e[MAX];

int main()

{

   while(~scanf("%d%d",&n,&m))

    {

        queue<int>s;

        memset(head,-1,sizeof(head));

        memset(degree,0,sizeof(degree));

        for(int i = 1; i <= n; i++)  ///總共n個人  每個人最少888元

            money[i] = 888;

        for(int i = 1; i <= m; i++)

        {

           scanf("%d%d",&a,&b);

            degree[a]++;  ///入度

            e[i].to = a;     

            e[i].next = head[b];    ///e[i].next表示a指向多少個點

            head[b] = i;    ///head數組用來儲存第幾個點

        }

        for(int i = 1; i <= n; i++)  ///總共n個人

        {

            if(degree[i]==0)

            {

                s.push(i);  ///把入度為零的進隊

            }

        }

        int sum = 0;

        int ans = 0;

        while(!s.empty())

        {

            int u = s.front();

            s.pop();

            sum+=money[u];

            ans++;

            for(int j = head[u]; j!=-1; j =e[j].next)  ///通過head數組來找到輸入u點的時候是第幾次

            {

                if(--degree[e[j].to]==0)   ///把下一個點入隊

                {

                    s.push(e[j].to);

                    money[e[j].to] = money[u] +1;   ///下一個點的獎金肯定比目前這個多

                }

            }

        }

        if(ans!=n)   ///如果調用的次數小于n  那麼可能中間有沖突 不能滿足條件

            printf("-1\n");

        else

            printf("%d\n",sum);

    }

    return 0;

}

繼續閱讀