一年之后又重新学习此算法。。。233。。。
1 #include<cstdio> 2 #include<iostream> 3 #include<cstring> 4 #include<cmath> 5 #include<ctime> 6 #include<cstdlib> 7 8 #include<string> 9 #include<stack> 10 //#include<queue> 11 #include<vector> 12 #include<algorithm> 13 #include<map> 14 #include<set> 15 16 using namespace std; 17 18 inline void read(int &x){ 19 x=0; 20 char t=getchar(); 21 bool f=0; 22 23 while(t<'0' || t>'9'){ 24 if(t=='-')f=1; 25 t=getchar(); 26 } 27 28 while(t>='0' && t<='9'){ 29 x=(x<<3)+(x<<1)+t-'0'; 30 t=getchar(); 31 } 32 33 if(f)x=-x; 34 } 35 36 struct que{ 37 int head,tail; 38 int q[10001]; 39 40 void build(){ 41 head=0; 42 tail=0; 43 } 44 45 bool emp(){ 46 return head==tail; 47 } 48 49 void push(int x){ 50 q[tail]=x; 51 tail++; 52 if(tail==10001)tail=0; 53 } 54 55 void pop(){ 56 head++; 57 if(head==10001)head=0; 58 } 59 60 int end(){ 61 if(tail==0)return q[10000]; 62 else return q[tail-1]; 63 } 64 65 int begin(){ 66 return q[head]; 67 } 68 }; 69 70 void start(); 71 void SPFA(); 72 73 que line; 74 bool pd[10010]; 75 int d[10010]; 76 77 int u[500010]; 78 int v[500010]; 79 int w[500010]; 80 int first[10010]; 81 int next[500010]; 82 83 int n,m,s,i; 84 85 int main(){ 86 start(); 87 88 read(n);read(m);read(s); 89 90 for(i=1;i<=m;i++){ 91 read(u[i]);read(v[i]);read(w[i]); 92 next[i]=first[u[i]]; 93 first[u[i]]=i; 94 } 95 96 SPFA(); 97 98 for(i=1;i<=n;i++){ 99 if(d[i]!=0x3f3f3f3f)printf("%d ",d[i]); 100 else printf("2147483647 "); 101 } 102 103 return 0; 104 } 105 106 void start(){ 107 line.build(); 108 memset(pd,0,sizeof(pd)); 109 memset(d,0x3f3f3f3f,sizeof(d)); 110 111 memset(first,0,sizeof(first)); 112 memset(next,0,sizeof(next)); 113 } 114 115 void SPFA(){ 116 int t; 117 118 line.push(s); 119 pd[s]=1; 120 d[s]=0; 121 122 while(!line.emp()){ 123 t=first[line.begin()]; 124 while(t!=0){ 125 if(d[v[t]]>d[u[t]]+w[t]){ 126 d[v[t]]=d[u[t]]+w[t]; 127 if(pd[v[t]]==0){ 128 line.push(v[t]); 129 pd[v[t]]=1; 130 } 131 } 132 t=next[t]; 133 } 134 pd[line.begin()]=0; 135 line.pop(); 136 } 137 }