struct Spfa {
struct Edge {
int next, to, w;
} e[maxm];
int head[maxn], v[maxn], d[maxn], tol;
void add(int u, int v, int w) {
tol++;
e[tol].to = v;
e[tol].next = head[u];
e[tol].w = w;
head[u] = tol;
}
queue<int> q;
int spfa(int s, int t) {
memset(d, 0x3f, sizeof(d));
memset(v, 0, sizeof(v));
d[s] = 0;
v[s] = 1;
q.push(s);
while (!q.empty()) {
int x = q.front();
q.pop();
v[x] = 0;
for (int i = head[x]; i; i = e[i].next) {
if (d[e[i].to] > d[x] + e[i].w) {
d[e[i].to] = d[x] + e[i].w;
if (v[e[i].to] == 0) {
v[e[i].to] = 1;
q.push(e[i].to);
}
}
}
}
return d[t] == 0x3f ? -1 : d[t];
}
void init() {
memset(head, 0, sizeof(head));
tol = 0;
}
} S;