拓扑排序求助,12分
  • 板块P1807 最长路
  • 楼主017_007
  • 当前回复1
  • 已保存回复1
  • 发布时间2023/3/12 18:12
  • 上次更新2023/10/23 21:44:45
查看原帖
拓扑排序求助,12分
931707
017_007楼主2023/3/12 18:12

nimade,做了好几天了

#include<bits/stdc++.h>
#include<queue>
#define ll long long
#define maxn 1510
#define maxm 50010
using namespace std;
ll n,m,u,v,w,cnt,first[maxn],post[maxn];
ll in[maxn];
struct node{
	ll to,next,w;
}edges[maxm];
bool d[maxn];
queue<ll>sx;
void bfs(){
	for (ll i=1;i<=n;++i) if (in[i]==0) sx.push(i),post[i]=0,d[i]=true;
	//for (ll i=1;i<=n;++i) printf("%lld\n",post[i]);
	while (!sx.empty()){
		ll t=sx.front();sx.pop();
		ll h=first[t];
		//printf("%lld\n",t);
		while (h){
			ll x1=edges[h].to,x2=edges[h].w;
			in[x1]--;
			if (in[x1]==0) sx.push(x1),d[x1]=true;
			post[x1]=max(post[x1],post[t]+w);
			//printf("%lld:%lld\n",x1,post[x1]);
			h=edges[h].next;
		}
	}
}
void add(ll u,ll v,ll w){
	edges[++cnt].to=v;
	edges[cnt].w=w;
	edges[cnt].next=first[u];
	first[u]=cnt;
}
int main(){
	scanf("%lld %lld",&n,&m);
	for (ll i=1;i<=m;++i) {
		scanf("%lld%lld%lld",&u,&v,&w);
		add(u,v,w);
		in[v]++;
	}
	memset(post,-20,sizeof(post));
	//for (ll i=1;i<=n;++i) printf("%lld\n",in[i]);
	bfs();
	if (!d[n]) printf("%lld\n",-1);
	else printf("%lld\n",post[n]);
	return 0;
}
2023/3/12 18:12
加载中...