洛谷P1113 雜務 拓撲排序

題目鏈接:https://www.luogu.com.cn/problem/P1113

題目讓我們求完成所有雜物的最短時間,實際上就是找一條關鍵路徑,這條關鍵路徑上的時間就是答案。找關鍵路徑可以用拓撲排序,當然拓撲排序只適用於有向無環圖(DAG),如果不是有向無環圖(DAG)是無法找完所有的點的。
這道題,要記錄兩個數組,每個節點的開始時間,和結束時間,在拓撲排序的過程中更新,最後遍歷結束時間的數組,最大的那個就是答案。
代碼如下

#include <bits/stdc++.h>
using namespace std;
const int maxn=1e4+5;
const int maxm=1e6+5;
struct node
{
    int to;
    int next;
}p[maxm];
struct que
{
    int key,value;
};
queue<que>q;
int n,cnt;
int cost[maxn];
int indeg[maxn];
int head[maxn];
int bg[maxn],ed[maxn];//節點開始時間與結束時間
void add(int x,int y)
{
    p[++cnt].next=head[x];
    p[cnt].to=y;
    head[x]=cnt;
}
void topo()//拓撲排序
{
    while(!q.empty())
    {
        que temp=q.front();
        q.pop();
        int u=temp.key,c=temp.value;
        ed[u]=bg[u]+c;
        for(int i=head[u];i;i=p[i].next)
        {
            int v=p[i].to;
            bg[v]=max(bg[v],ed[u]);
            indeg[v]--;
            if(!indeg[v])//入度爲0入隊
            q.push({v,cost[v]});
        }
    }
}
int main()
{
    scanf("%d",&n);
    int x,y;
    for(int i=1;i<=n;i++)
    {
        scanf("%d",&y);
        scanf("%d",&cost[y]);
        while(~scanf("%d",&x)&&x)
        {
            add(x,y);
            indeg[y]++;
        }
        if(!indeg[y])
        q.push({y,cost[y]});
    }
    topo();
    int ans=0;
    for(int i=1;i<=n;i++)
    ans=max(ans,ed[i]);//更新節點最大值爲答案
    printf("%d\n",ans);
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章