题意:
给定一个有向无环图,求该图的最长路。
思路:
由于是有向无环图,所以最长路肯定是一个入度为0到出度为0的路径,拓扑序在确定当前点之前能够考虑到所有到它的情况,所以最后取个最值即可。
代码:
#include <bits/stdc++.h>
using namespace std;
const int inf = 0x3f3f3f3f;
const int maxn = 1e4+5;
const int maxm = 1e5+5;
struct node{int v, w, next;} edge[maxm];
int no, head[maxn];
int t, n, m;
int deg[maxn], val[maxn];
queue<int> q;
void init()
{
no = 0;
memset(head, -1, sizeof head);
memset(deg, 0, sizeof deg);
memset(val, 0, sizeof val);
}
inline void add(int u, int v, int w)
{
edge[no].v = v; edge[no].w = w;
edge[no].next = head[u]; head[u] = no++;
}
void topsort()
{
while(!q.empty()) q.pop();
for(int i = 1; i <= n; ++i)
if(!deg[i]) q.push(i);
int ans = 0;
while(!q.empty())
{
int u = q.front(); q.pop();
for(int k = head[u]; k+1; k = edge[k].next)
{
int v = edge[k].v;
val[v] = max(val[v], edge[k].w+val[u]);
if(--deg[v] == 0) q.push(v);
}
}
printf("%d\n", *max_element(val+1, val+n+1));
}
int main()
{
for(scanf("%d", &t); t--;)
{
scanf("%d %d", &n, &m); init();
for(int i = 1; i <= m; ++i)
{
int u, v, w;
scanf("%d %d %d", &u, &v, &w);
add(u, v, w); ++deg[v];
}
topsort();
}
return 0;
}
继续加油~