1 //Accepted 2692 KB 1282 ms 2 //差分约束 -->最短路 3 //TLE到死,加了输入挂,手写queue 4 #include <cstdio> 5 #include <cstring> 6 #include <iostream> 7 #include <queue> 8 #include <cmath> 9 #include <algorithm> 10 using namespace std; 11 /** 12 * This is a documentation comment block 13 * 如果有一天你坚持不下去了,就想想你为什么走到这儿! 14 * @authr songt 15 */ 16 const int imax_n = 30005; 17 const int imax_e = 150005; 18 const int inf = 0x3f3f3f3f; 19 struct node 20 { 21 int u,v,c; 22 node(int u=0,int v=0,int c=0):u(u),v(v),c(c) 23 { 24 25 } 26 }p[imax_e]; 27 int e=0; 28 int head[imax_n]; 29 int next[imax_e]; 30 int dis[imax_n]; 31 bool vis[imax_n]; 32 int n,m; 33 void addEdge(int u,int v,int c) 34 { 35 //p[e]=node(u,v,c); 36 p[e].u=u; 37 p[e].v=v; 38 p[e].c=c; 39 next[e]=head[u]; 40 head[u]=e++; 41 } 42 bool relax(int u,int v,int c) 43 { 44 if (dis[v]>dis[u]+c) 45 { 46 dis[v]=dis[u]+c; 47 return true; 48 } 49 return false; 50 } 51 void init() 52 { 53 memset(head,-1,(n+2)*sizeof(head[0])); 54 memset(next,-1,(n+2)*sizeof(next[0])); 55 e=0; 56 } 57 //queue<int > q; 58 int q[imax_e]; 59 int top; 60 void spfa(int src) 61 { 62 //while (!q.empty()) q.pop(); 63 //memset(vis,0,(n+2)*sizeof(vis[0])); 64 for (int i=1;i<=n;i++) 65 { 66 dis[i]=inf; 67 vis[i]=0; 68 } 69 dis[src]=0; 70 //q.push(src); 71 top=1; 72 q[0]=src; 73 vis[src]=true; 74 while (top) 75 { 76 //int pre=q.front(); 77 //q.pop(); 78 int pre=q[--top]; 79 80 vis[pre]=false; 81 for (int i=head[pre];i+1;i=next[i]) 82 { 83 if (relax(pre,p[i].v,p[i].c) && !vis[p[i].v]) 84 { 85 vis[p[i].v]=true; 86 //q.push(p[i].v); 87 q[top++]=p[i].v; 88 } 89 } 90 } 91 } 92 /** 93 * 读取一个int 94 */ 95 inline int read_int() 96 { 97 int ret=0; 98 char tmp; 99 while(!isdigit(tmp=getchar())); 100 do{ 101 ret=(ret<<3)+(ret<<1)+tmp-‘0‘; 102 }while(isdigit(tmp=getchar())); 103 return ret; 104 } 105 106 int main() 107 { 108 //while (scanf("%d%d",&n,&m)!=EOF) 109 scanf("%d%d",&n,&m); 110 { 111 init(); 112 int u,c,v; 113 for (int i=0;i<m;i++) 114 { 115 u=read_int(); 116 v=read_int(); 117 c=read_int(); 118 addEdge(u,v,c); 119 } 120 spfa(1); 121 printf("%d\n",dis[n]); 122 } 123 return 0; 124 }
时间: 2024-12-05 06:04:24