题意介绍
有若干城市,从一个城市到另一个城市需要交税(可能为负值),求给出城市到首都索要交的税。
题意分析
该题要求单源最短路径,并且存在负边的情况,只能用SPFA算法。在SPFA时要将存在与负环中的点标记出来,判断负环的条件为点出现在队列中的次数大于等于中的点数。输出"?"的条件为该点出现在负环中或者不可到达或者要缴纳的税小于3.
#include<iostream>
#include<string.h>
#include<queue>
using namespace std;
const int inf=0x3f3f3f3f;
int t, n, m, u, v, q, p;
int a[210];
int head[210], tot;
queue<int> que;
int dis[210], inq[210], cnt[210],vis[210];
struct edge {
int to, next, w;
}edge[100010];
void init() {
tot = 0;
memset(head, -1, sizeof(head));
}
void add(int x, int y, int w) {
edge[tot].to = y;
edge[tot].w = w;
edge[tot].next = head[x];
head[x] = tot;
tot++;
}
void dfs(int u) {
vis[u] = 1;
for (int i = head[u]; i != -1; i = edge[i].next) {
if(vis[edge[i].to]==0)
dfs(edge[i].to);
}
}
void spfa(int s) {
while (!que.empty()) que.pop();
for (int i = 1; i <= n; i++) {
dis[i] = inf;
inq[i] = 0;
cnt[i] = 0;
vis[i] = 0;
}
dis[s] = 0;
inq[s] = 1;
que.push(s);
while (!que.empty()) {
int u = que.front();
que.pop();
inq[u] = 0;
for (int i = head[u]; i != -1; i = edge[i].next) {
int v = edge[i].to, w = edge[i].w;
if (vis[v]) continue;
if (dis[v] > dis[u] + w) {
dis[v] = dis[u] + w;
if (!inq[v]) {
que.push(v);
inq[v] = 1;
cnt[v]++;
if (cnt[v] >= n) {//找到负环
dfs(v);
}
}
}
}
}
}
int main() {
cin >> t;
int item = 1;
while (t--) {
cin >> n;
for (int i = 1; i <= n; i++) cin >> a[i];
init();
cin >> m;
for (int i = 0; i < m; i++) {
cin >> u >> v;
add(u, v, (a[v] - a[u])*(a[v] - a[u])*(a[v] - a[u]));
}
spfa(1);
cout << "Case" << " " << item << ":"<<endl;
cin >> q;
while (q--) {
cin >> p;
if (vis[p] == 0) {
//cout << dis[p] << endl;
if (dis[p] < 3||dis[p]==inf)cout << "?" << endl;
else cout << dis[p] << endl;
}
else
cout << "?" << endl;
}
item++;
}
return 0;
}```