题目链接:Source
题面:
Solution
暴力建边肯定不行,所以可以对每一个城市群建立一个超级出点和入点,内部城市到出点、入点到内部城市分别建耗费为0的边,城市群之间则按照出点->入点 入点 -> 出点 的规则建边,最后直接跑最短路即可
Code
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int INF = 0x3f3f3f3f;
const ll LINF = 0x3f3f3f3f3f3f3f3f;
const int maxn = 1e5 + 7;
const int maxm = 4e5 + 7;
int n,m,m1,m2,s,t;
struct Edge{
int v,w,next;
}e[maxm << 1];
int ecnt,head[maxn];
void add(int u,int v,int w){
e[++ecnt].v = v, e[ecnt].w = w, e[ecnt].next = head[u], head[u] = ecnt;
}
struct node{
int now;
ll w;
inline bool operator<(const node&it) const{
return w > it.w;
}
};
ll dis[maxn];bool vis[maxn];
ll dijkstra(){
priority_queue<node>q;
for(int i = 1;i <= n + n + m;++i){
vis[i] = false, dis[i] = LINF;
}
dis[s] = 0;q.push((node){s,0});
while(!q.empty()){
node tmp = q.top();q.pop();
int u = tmp.now;
if(vis[u]) continue;vis[u] = true;
for(int i = head[u];i;i = e[i].next){
int v = e[i].v;ll w = e[i].w;
if(dis[v] >= w + dis[u]) {
dis[v] = w + dis[u];q.push((node){v,dis[v]});
}
}
}
return dis[t];
}
int main(){
scanf("%d%d",&n,&m);
for(int i = 1;i <= m;++i){
int num;scanf("%d",&num);
int out = n + i, in = n + n + i;
while(num--){
int v;scanf("%d",&v);
add(v,out,0);add(in,v,0);
}
}
scanf("%d",&m1);
for(int i = 1;i <= m1;++i){
int u,v,w;scanf("%d%d%d",&u,&v,&w);add(u,v,w);add(v,u,w);
}
scanf("%d",&m2);
for(int i = 1;i <= m2;++i){
int u,v,w;scanf("%d%d%d",&u,&v,&w);
int outu = n + u, inu = n + n + u;
int outv = n + v, inv = n + n + v;
add(outu,inv,w);add(outv,inu,w);
}
scanf("%d%d",&s,&t);
ll res = dijkstra();
if(res == LINF) res = -1;
printf("%lld\n", res);
return 0;
}