[USACO10FEB]给巧克力Chocolate Giving

mac2022-06-30  117

题意简叙:

FarmerFarmerFarmer JohnJohnJohn有B头奶牛(1<=B<=25000)(1<=B<=25000)(1<=B<=25000),有N(2∗B<=N<=50000)N(2*B<=N<=50000)N(2B<=N<=50000)个农场,编号1−N1-N1N,有M(N−1<=M<=100000)M(N-1<=M<=100000)M(N1<=M<=100000)条双向边,第i条边连接农场RiR_iRiSi(1<=Ri<=N;1<=Si<=N)S_i(1<=R_i<=N;1<=S_i<=N)Si(1<=Ri<=N;1<=Si<=N),该边的长度是Li(1<=Li<=2000)L_i(1<=L_i<=2000)Li(1<=Li<=2000)。居住在农场PiP_iPi的奶牛A(1<=Pi<=N)A(1<=P_i<=N)A(1<=Pi<=N),它想送一份新年礼物给居住在农场Qi(1<=Qi<=N)Q_i(1<=Q_i<=N)Qi(1<=Qi<=N)的奶牛B,但是奶牛A必须先到FJ(居住在编号1的农场)那里取礼物,然后再送给奶牛B。你的任务是:奶牛A至少需要走多远的路程?

题目分析:

不难看出,这就是一道单元最短路的裸题

我们可以首先用dijkstra单源最短路跑出1到所有点之间的最短路径,然后每问一次就调用一次即可,具体见代码。

代码:

#include<cstdio> #include<queue> #include<vector> using namespace std; #define pa pair<int,int> #define maxn 100010 priority_queue<pa,vector<pa>,greater<pa> > q; struct edge { int val,to; }; int n,m,s,dis[maxn]; bool vis[maxn]; vector<edge>e[maxn]; int main() { int b; scanf("%d%d%d",&n,&m,&b); s=1; for(int i=1;i<=m;i++) { int x,y,z; scanf("%d%d%d",&x,&y,&z); edge tmp; tmp.to=y; tmp.val=z; e[x].push_back(tmp); tmp.to=x; tmp.val=z; e[y].push_back(tmp);//注意这里一定要存储双向边 } //start for(int i=1;i<=n;i++) { dis[i]=2147483647;//初始化 } dis[s]=0; q.push(make_pair(0,s)); while(q.empty()==0) { int x=q.top().second; q.pop(); if(vis[x]==1) continue; vis[x]=1; for(int i=0;i<e[x].size();i++) { int y=e[x][i].to; if(dis[x]+e[x][i].val<dis[y]) { dis[y]=dis[x]+e[x][i].val; q.push(make_pair(dis[y],y)); } } } //finish //以上的部分皆为dijkstra标准模板,写的还算比较正规,感谢趣的同志可以收藏一下。(逃 for(int i=1;i<=b;i++) { int x,y; scanf("%d%d",&x,&y); printf("%d\n",dis[x]+dis[y]);//直接调用 } return 0; }

转载于:https://www.cnblogs.com/vercont/p/10210087.html

相关资源:Job Hunting - every thing you need to know
最新回复(0)