题目就是求路径中任意两条边颜色不同的最短路径。然后思路就是记录最短路和与最短路颜色不同的最短路,其实就是最短路和次短路(不同颜色),然后dijkstra算法优先队列搞一下就好了。
#pragma warning(disable:4996)
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#include <iostream>
using namespace std;
typedef long long LL;
const LL inf = 10000000000000000LL;
const int N = 100005;
struct node {
LL len;
int pos, col;
node(){}
node(int pos, LL len, int col) :pos(pos), len(len), col(col) {}
bool operator<(const node &op)const {
return len > op.len;
}
};
int fst[N], nxt[N], to[N], c[N], w[N], e;
int n, m, C;
LL dis[N][2];//0->最小,1->跟最小颜色不同的次小
int color[N][2];//相应颜色
void add(int u, int v, int len, int col) {
to[e] = v;
w[e] = len;
c[e] = col;
nxt[e] = fst[u];
fst[u] = e++;
}
void dijkstra(int s) {
priority_queue<node>q;
for (int i = 1; i <= n; i++) {
dis[i][0] = dis[i][1] = inf;
}
memset(color, 0, sizeof color);
dis[s][0] = dis[s][1] = 0;
q.push(node(s, 0, 0));
while (!q.empty()) {
node now = q.top(); q.pop();
int u = now.pos;
for (int i = fst[u]; ~i; i = nxt[i]) {
int v = to[i], col = c[i], len = w[i];
if (col == now.col)continue;
if (dis[v][0] > now.len + len) {
dis[v][0] = now.len + len;
color[v][0] = col;
q.push(node(v, dis[v][0], color[v][0]));
}
//注意这里判断一下颜色不能跟最短路的一样!!!
else if (color[v][0] != col&&dis[v][1] > now.len + len) {
dis[v][1] = now.len + len;
color[v][1] = col;
q.push(node(v, dis[v][1], color[v][1]));
}
}
}
}
int main() {
e = 0;
memset(fst, -1, sizeof fst);
scanf("%d%d%d", &n, &m, &C);
for (int i = 1; i <= m; i++) {
int u, v, len, col;
scanf("%d%d%d%d", &u, &v, &len, &col);
add(u, v, len, col);
}
int q, s;
scanf("%d%d", &s, &q);
dijkstra(s);
while (q--) {
int t; scanf("%d", &t);
if (dis[t][0] == inf)dis[t][0] = -1;
printf("%I64d\n", dis[t][0]);
}
return 0;
}