bzoj2015[Usaco2010 Feb]Chocolate Giving*
bzoj2015[Usaco2010 Feb]Chocolate Giving
题意:
n点m边无向图,有k头奶牛要送礼,它必须去农场(1号节点)拿礼物然后到目的地送。问每只奶牛的最短距离。n≤50000
题解:
以1号节点为源点spfa求一次最短路即可(反正是无向边)。
代码:
1 #include <cstdio> 2 #include <cstring> 3 #include <algorithm> 4 #include <queue> 5 #define ll long long 6 #define inc(i,j,k) for(int i=j;i<=k;i++) 7 #define maxn 50010 8 #define INF 0x3fffffff 9 using namespace std; 10 11 inline ll read(){ 12 char ch=getchar(); ll f=1,x=0; 13 while(ch<'0'||ch>'9'){if(ch=='-')f=-1; ch=getchar();} 14 while(ch>='0'&&ch<='9')x=x*10+ch-'0',ch=getchar(); 15 return f*x; 16 } 17 18 struct e{int t,w,n;}; e es[maxn*4]; int g[maxn],ess; 19 void pe(int f,int t,int w){es[++ess]=(e){t,w,g[f]}; g[f]=ess; es[++ess]=(e){f,w,g[t]}; g[t]=ess;} 20 int n,m,b,d[maxn]; bool inq[maxn]; queue<int>q; 21 void spfa(){ 22 while(!q.empty())q.pop(); memset(inq,0,sizeof(inq)); inc(i,1,n)d[i]=INF; 23 q.push(1); inq[1]=1; d[1]=0; 24 while(!q.empty()){ 25 int x=q.front(); q.pop(); inq[x]=0; 26 for(int i=g[x];i;i=es[i].n)if(d[es[i].t]>d[x]+es[i].w){ 27 d[es[i].t]=d[x]+es[i].w; if(!inq[es[i].t])q.push(es[i].t),inq[es[i].t]=1; 28 } 29 } 30 } 31 int main(){ 32 n=read(); m=read(); b=read(); 33 inc(i,1,m){int a=read(),b=read(),c=read(); pe(a,b,c);} spfa(); 34 inc(i,1,b){int a=read(),b=read(); printf("%d\n",d[a]+d[b]);} return 0; 35 }
20160811