我都要醉了~以为SPFA不够快,写了Dijkstra还是超时!!!已经用了快速读入
#include<cstdio>//Dijkstra
#include<cstring>
#include<queue>
#include<iostream>
#include<algorithm>
using namespace std;
const int N=102;
const int M=20002;
int w[N][N],t,route[M],dis[N],n,m;
long long ans;
bool inq[N];
int ALIKE_fast(){
int tot=0;char c;
c=getchar();
while(1){
if(c>='0'&&c<='9')
break;
c=getchar();
}
while(1){
tot=tot*10+c-'0';
c=getchar();
if(c<'0'||c>'9')
break;
}
return tot;
}
void ALIKE_Dijkstra(int sta){
int i,v;
memset(inq,false,sizeof(inq));
for(i=1;i<=n;i++)
dis[i]=1<<30;
dis[sta]=0;
while(1){
v=-1;
for(i=1;i<=n;i++)
if(inq[i]==false&&dis[i]!=1<<30&&(v==-1||dis[i]<dis[v]))
v=i;
if(v==-1)
break;
inq[v]=true;
for(i=1;i<=n;i++)
if(w[v][i]!=-1)
dis[i]=min(dis[i],dis[v]+w[v][i]);
}
}
int main(){
int i,j;
memset(w,-1,sizeof(w));
n=ALIKE_fast();m=ALIKE_fast();
for(i=1;i<=m;i++)
route[i]=ALIKE_fast();
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
w[i][j]=ALIKE_fast();
for(i=0,route[0]=1,route[m+1]=n;i<=m;i++){
ALIKE_Dijkstra(route[i]);
ans+=dis[route[i+1]];
}
cout<<ans<<endl;
return 0;
}
//SPFA
#include<cstdio>
#include<cstring>
#include<queue>
#include<iostream>
using namespace std;
const int N=102;
const int M=20002;
int h[M],w[M],to[M],nxt[M],t,route[M],dis[N],n,m;
long long ans;
bool inq[N];
int ALIKE_fast(){
int tot=0;char c;
c=getchar();
while(1){
if(c>='0'&&c<='9')
break;
c=getchar();
}
while(1){
tot=tot*10+c-'0';
c=getchar();
if(c<'0'||c>'9')
break;
}
return tot;
}
void ALIKE_ADD_EDGE(int u,int v,int W){
t++;
nxt[t]=h[u];
h[u]=t;
w[t]=W;
to[t]=v;
return ;
}
void ALIKE_SPFA(int sta){
queue<int> q;
int v,u;
memset(inq,false,sizeof(inq));
for(v=1;v<=n;v++)
dis[v]=1<<30;
dis[sta]=0;
inq[sta]=true;
q.push(sta);
while(q.empty()==false){
u=q.front();
q.pop();
inq[u]=false;
for(v=h[u];v;v=nxt[v])
if(dis[to[v]]>dis[u]+w[v]){
dis[to[v]]=dis[u]+w[v];
if(inq[to[v]]==false){
inq[to[v]]=true;
q.push(to[v]);
}
}
}
}
int main(){
int x,i,j;
n=ALIKE_fast();m=ALIKE_fast();
for(i=1;i<=m;i++)
route[i]=ALIKE_fast();
for(i=1;i<=n;i++)
for(j=1;j<=n;j++){
x=ALIKE_fast();
ALIKE_ADD_EDGE(i,j,x);
}
for(i=0,route[0]=1,route[m+1]=n;i<=m;i++){
ALIKE_SPFA(route[i]);
ans+=dis[route[i+1]];
}
cout<<ans<<endl;
return 0;
}