#define _CRT_SECURE_NO_WARNINGS
#include<cstdio>
#include<bits/stdc++.h>
using namespace std;
int N, M, C1, C2;
int const maxn = 510;
int const INF = 1000000000;
int weight[maxn];
struct Node {
int v;
int d;
};
vector<Node> Adj[maxn];
int d[maxn];
set<int>pre[maxn];
int num[maxn];
int w[maxn];
int inqnum[maxn] = { 0 };
bool inq[maxn] = { false };
bool bellman(int s)
{
fill(d, d + maxn, INF);
fill(num, num + maxn, 0);
fill(w, w + maxn, 0);
w[s] = weight[s];
d[s] = 0;
num[s] = 1;
queue <int>q;
q.push(s);
inqnum[s]++;
inq[s] = true;
while (!q.empty())
{
int u = q.front();
q.pop();
inq[u] = false;
for (int i = 0; i < Adj[u].size(); i++)
{
int v = Adj[u][i].v;
int dis= Adj[u][i].d;
if (d[v] > d[u] + dis)
{
d[v] = d[u] + dis;
w[v] = w[u] + weight[v];
num[v] = num[u];
pre[v].clear();
pre[v].insert(u);
if (!inq[v])
{
q.push(v);
inq[v] = true;
inqnum[v]++;
if (inqnum[v] >= N)
return false;
}
}
else if (d[v] == d[u] + dis)
{
if (w[u] + weight[v] > w[v])
{
w[v] = w[u] + weight[v];
}
pre[v].insert(u);
num[v] =0;
for (set<int>::iterator it = pre[v].begin(); it != pre[v].end(); it++)
{
num[v] += num[*it];
}
if (!inq[v])
{
q.push(v);
inq[v] = true;
inqnum[v]++;
if (inqnum[v] >= N)
return false;
}
}
}
}
return true;
}
int main()
{
scanf("%d %d %d %d", &N, &M, &C1, &C2);
for (int i = 0; i < N; i++)
{
int w;
scanf("%d", &w);
weight[i] = w;
}
for (int i = 0; i < M; i++)
{
int a, b, d;
scanf("%d %d %d", &a, &b, &d);
Node pab;
pab.v = b;
pab.d = d;
Adj[a].push_back(pab);
Node pba;
pba.v = a;
pba.d = d;
Adj[b].push_back(pba);
}
if (bellman(C1))
{
printf("%d %d", num[C2], w[C2]);
}
return 0;
}
注意
这里必须加上入队操作,不然w就无法更新成功就会出现错误
else if (d[v] == d[u] + dis)
{
if (w[u] + weight[v] > w[v])
{
w[v] = w[u] + weight[v];
}
pre[v].insert(u);
num[v] =0;
for (set<int>::iterator it = pre[v].begin(); it != pre[v].end(); it++)
{
num[v] += num[*it];
}
if (!inq[v])
{
q.push(v);
inq[v] = true;
inqnum[v]++;
if (inqnum[v] >= N)
return false;
}
}
}