思路
题目描述
设 G 为有 n 个顶点的带权有向无环图,G 中各顶点的编号为 1 到 n,请设计算法,计算图 G 中 <1,n> 间的最长路径。
有向无环图 这个条件可以告诉我们可以使用 拓扑排序
(当然可以用单源最短路径相关算法)
细节
- 一个变量sum,记录遍历过的所有点的总数,总数小于n继续遍历
- 用栈来实现递归时,注意栈内有多少个数,栈内没有数就不用继续遍历
- 因为是求1到n的各点距离,所以先要从1点开始遍历
代码
#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
int n,m;
const int maxn=1e4+10;
const int maxm=5e5+10;
struct node{
int v,next,w;
}e[maxm];
int r[maxn];
int head[maxm];
int cnt=0;
int top=0;
int dis[maxn];
int ans[maxn];
void add(int u,int v,int w){
e[++cnt].v=v;
e[cnt].w=w;
e[cnt].next=head[u];
head[u]=cnt;
}
int main(){
memset(head,