//差分约束系统 //建立关系十分简单,SPFA求到终点的距离 //但这一题十分奇怪,用队列就TLE,用栈就不会,真奇怪~ #include<iostream> #include<stack> #define MAXN 30005 #define MAXM 150000 #define INF 1000000000 using namespace std; int N,M,m,u,v,w; bool inq[MAXN]; int dis[MAXN]; int head[MAXN],next[MAXM],V[MAXM],W[MAXM]; inline void addEdge(int u,int v,int w) { V[m] = v; W[m] = w; next[m] = head[u]; head[u] = m++; } void buildGraph() { m = 0; scanf("%d%d",&N,&M); memset(head,-1,sizeof(head)); while(M--) { scanf("%d%d%d",&u,&v,&w); addEdge(u,v,w); } } int SPFA() { for(int i = 2;i <= N;++i) dis[i] = INF; dis[1] = 0; stack<int> q;//用堆栈来做就不会超时了 q.push(1); inq[1] = 1; while(!q.empty()) { int u = q.top(); q.pop(); inq[u] = 0; for(int e = head[u];e != -1;e = next[e]) { if(dis[u] + W[e] < dis[V[e]]) { dis[V[e]] = dis[u] + W[e]; if(!inq[V[e]]) { q.push(V[e]); inq[V[e]] = 1; } } } } return dis[N];//返回终点的距离就是答案 } int main() { buildGraph(); printf("%d/n",SPFA()); return 0; }