//差分约束 >=求最长路径 <=求最短路径 结果都一样
//spfa
#include<stdio.h> #include<string.h> #include<limits.h> #include<queue> using namespace std; #define N 1010 #define M 1010*1010//注意边和点集的数组大小 struct edge { int to,value,next; }; struct edge edges[M]; int heads[N],len=0; int dis[N]; int addedge(int u,int v,int w) { edges[len].to=v,edges[len].value=w,edges[len].next=heads[u]; heads[u]=len++; return 0; } int n,m; int spfa(int v) { queue<int> q; int inqueue[N]; memset(inqueue,0,sizeof(inqueue)),inqueue[v]=1; q.push(v); for(int i=0;i<=n;i++) dis[i]=INT_MIN; dis[v]=0; int times[N]; memset(times,0,sizeof(times)),times[v]=1; int temp=0; while(!q.empty()){ int x=q.front(); q.pop(); inqueue[x]=0; for(int i=heads[x];i!=-1;i=edges[i].next){ int to=edges[i].to,value=edges[i].value; if(value+dis[x]>dis[to]){ dis[to]=value+dis[x]; if(!inqueue[to]){ //注意已经在队列里面的不用再加入队列 inqueue[to]=1,q.push(to); times[to]++; if(times[x]>n){ return -1;//返回值有可能是0 不能将0作为区别的标记 } } } } } return dis[n]; } int main(void) { int i,num; while(scanf("%d%d",&n,&m)!=EOF){ len=0; memset(heads,-1,sizeof(heads)); for(i=1;i<=n;i++){ scanf("%d",&num); addedge(i,i-1,-num); addedge(0,i,0); } for(i=1;i<=m;i++){ int u,v,w; scanf("%d%d%d",&u,&v,&w); addedge(u-1,v,w); } int h=spfa(0); if(h!=-1) printf("%d ",h); else printf("Bad Estimations "); } return 0; }
//bellman
#include <iostream> #include <stdio.h> #include <string.h> using namespace std; #define INF 2000000000 int u[12005],v[12005],w[12005],n,m,total,d[1005]; void Edge(int s,int e,int val){ u[total]=s; v[total]=e; w[total++]=val; } int Bellman(){ int i,e; for(i=1;i<=n;i++) d[i]=-INF; d[0]=0; for(i=1;i<=n;i++){ for(e=0;e<total;e++){ if(d[v[e]]<d[u[e]]+w[e]) d[v[e]]=d[u[e]]+w[e]; } } int ans=d[n]; for(e=0;e<total;e++) if(d[v[e]]<d[u[e]]+w[e]) ans=-1; return ans; } int main(){ int a,b,c,cnt,i; while(scanf("%d%d",&n,&m)!=EOF){ total=0; for(i=1;i<=n;i++){ scanf("%d",&c); Edge(0,i,0); Edge(i,i-1,-c); } for(i=0;i<m;i++){ scanf("%d%d%d",&a,&b,&c); Edge(a-1,b,c); } cnt=Bellman(); for(i=0;i<n;i++) printf("%d ",d[i]); puts(""); if(cnt==-1) cout<<"Bad Estimations "; else cout<<cnt<<" "; } return 0; }