hdoj 4109--Instrction Arrangement(topsort)

题解

实际上就是按照拓扑序求关键路径。

#include 
#include 
#include 
#include 
using namespace std;

const int maxn = 1000 + 10;
int n, m;

struct Edge{
    int v, w, next;
}edge[10010];

int head[maxn], cnt;
int indeg[maxn];
int dis[maxn];

void sol(){
    queue<int> Q;

    for(int i = 0; i < n; ++i){
        if(indeg[i] == 0){
            Q.push(i);
            dis[i] = 1;
        }
    }

    while(!Q.empty()){
        int u = Q.front();
        Q.pop();
        for(int i = head[u]; ~i; i = edge[i].next){
            int v = edge[i].v, w = edge[i].w;
            dis[v] = max(dis[v], dis[u] + w);
            if(--indeg[v] == 0) Q.push(v);
        }
    }
    int ans = 0;
    for(int i = 0; i < n; ++i){
        ans = max(ans, dis[i]);
    }

    printf("%d\n", ans);
}


void addEdge(int u, int v, int w){
    edge[cnt].v = v; 
    edge[cnt].w = w;
    edge[cnt].next = head[u];
    head[u] = cnt++;
}

int main(){

    int u, v, w;
    while(~scanf("%d %d", &n, &m)){
        memset(dis, 0, sizeof(dis));
        memset(indeg, 0, sizeof(indeg));
        memset(head, -1, sizeof(head));
        cnt = 0;

        for(int i = 0; i < m; ++i){
            scanf("%d %d %d", &u, &v, &w);
            addEdge(u, v, w);
            indeg[v]++;
        }
        sol();
    }

    return 0;
}

你可能感兴趣的:(图论,图论--拓扑排序)