牛客小白月赛16 J小雨坐地铁 分层图最短路
作者:互联网
题目链接:https://ac.nowcoder.com/acm/contest/949/J
中文体不解释题意
思路:分层图最短路,每一条线建一层图,同时建一层虚点,每一层图的所有点都与虚点建两条边,虚点到该点的代价为上该条线的价格,该点到虚点的代价位0,建完图之后从虚点上车同时从虚点下车(因为不知道最后从哪一条线路下车,但虚点一定会下车)
AC代码:
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<queue>
#include<vector>
#include<cmath>
#include<stack>
#include<map>
#include<set>
using namespace std;
#define LL long long
const int MOD=1e9+7;
const int inf=0x3f3f3f3f;
const LL inff=0x3f3f3f3f3f3f3f3f;
const LL N=205;
const LL M=5005;
const double pi=acos(-1);
#define MEF(x) memset(x,-1,sizeof(x))
#define ME0(x) memset(x,0,sizeof(x))
#define MEI(x) memset(x,inf,sizeof(x))
int first[1000005],cnt,dis[505*1005],vis[505*1005],n,m,cl[1005];
struct edge
{
int v,w,next;
}edg[1000005];
struct node
{
LL diss,s;
friend bool operator <(const node a,const node b)
{
return a.diss>b.diss;
}
};
void init()
{
MEF(first);
cnt=0;
MEI(dis);
ME0(vis);
}
void add(int u,int v,int w)
{
edg[++cnt].v=v;
edg[cnt].w=w;
edg[cnt].next=first[u];
first[u]=cnt;
}
void dijstra(int s,int t)
{
priority_queue<node> pq;
dis[s+m*n]=0;
pq.push((node){0,s+m*n});
while(!pq.empty())
{
int st=pq.top().s;
pq.pop();
if(vis[st])
{
continue;
}
vis[st]=1;
for(int i=first[st];i!=-1;i=edg[i].next)
{
int lv=edg[i].v;
if(!vis[lv]&&dis[lv]>dis[st]+edg[i].w)
{
dis[lv]=dis[st]+edg[i].w;
pq.push((node){dis[lv],lv});
}
}
}
}
int main()
{
int s,t;
cin>>n>>m>>s>>t;
init();
for(int m1=1;m1<=m;m1++)
{
int a,b,c;
cin>>a>>b>>c;
for(int c1=1;c1<=c;c1++)
{
cin>>cl[c1];
add(cl[c1]+(m1-1)*n,cl[c1]+m*n,0);
add(cl[c1]+m*n,cl[c1]+(m1-1)*n,a);
if(c1>=2)
{
add(cl[c1-1]+(m1-1)*n,cl[c1]+(m1-1)*n,b);
add(cl[c1]+(m1-1)*n,cl[c1-1]+(m1-1)*n,b);
}
}
}
dijstra(s,t);
if(dis[t+m*n]==inf)
{
cout<<-1<<endl;
}
else
{
cout<<dis[t+m*n]<<endl;
}
return 0;
}
标签:edg,16,int,cl,牛客,小白月赛,c1,include,dis 来源: https://blog.csdn.net/ecjtu_17_TY/article/details/95877022