Dhaka city is getting crowded and noisy day by day. Certain roads always remain blocked in congestion. In order to convince people avoid shortest routes, and hence the crowded roads, to reach destination, the city authority has made a new plan. Each junction of the city is marked with a positive integer (≤ 20) denoting the busyness of the junction. Whenever someone goes from one junction (the source junction) to another (the destination junction), the city authority gets the amount (busyness of destination - busyness of source)3 (that means the cube of the difference) from the traveler. The authority has appointed you to find out the minimum total amount that can be earned when someone intelligent goes from a certain junction (the zero point) to several others.
当1到该点的距离小于3或无法到达该点时,输出?,否则输出距离。
当图中存在负圈时,从负圈可达点都要输出?
spfa算法
#include<cstring>
#include<iostream>
#include<math.h>
#include<queue>
#include<vector>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
#define N 4000+5
//#define mem(arr,a) memset(arr,a,sizeof(arr))
#define INF 0x3f3f3f3f
#define pow(a) ((a)*(a)*(a))
struct edge{
int to, cost;
};
int d[N];
int vis[N];
int num[N];
int arr[N];
int marks[N];
int t, n, m;
vector<edge> es[N];
void add(int a, int b){
edge e; e.to = b; e.cost = pow(arr[b] - arr[a]);
es[a].push_back(e);
}
void dfs(int s){
marks[s] = 1;
for (int i = 0; i < es[s].size();i++)
if (!marks[es[s][i].to])
marks[es[s][i].to] = 1;
}
void spfa(int s){
memset(d, INF, sizeof(d));
memset(num, 0, sizeof(num));
memset(vis, 0, sizeof(vis));
memset(marks, 0, sizeof(marks));
queue<int>q;
d[s] = 0;
q.push(s);
num[s] = 1;
while (!q.empty()){
int x = q.front(); q.pop(); vis[x] = 0;
if (marks[x])continue;
for (int i = 0; i < es[x].size(); i++){
edge e = es[x][i];
if (d[e.to]>d[x] + e.cost){
d[e.to] = d[x] + e.cost;
if (!vis[e.to]){
vis[e.to] = 1;
num[e.to]++;
q.push(e.to);
if (num[e.to] == n){
dfs(e.to);
}
}
}
}
}
}
int main(){
cin >> t;
int cnt = 1;
while (t--){
scanf("%d", &n);
for (int i = 1; i <= n; i++){
scanf("%d", &arr[i]);
es[i].clear();
}
scanf("%d", &m);
for (int i = 1; i <= m; i++){
int a, b; scanf("%d%d", &a, &b);
add(a, b);
}
spfa(1);
int q;
scanf("%d", &q);
printf("Case %d:\n", cnt++);
for (int i = 1; i <= q; i++){
int a; scanf("%d", &a);
if (marks[a] || d[a] < 3 || d[a] == INF)printf("?\n");
else printf("%d\n", d[a]);
}
}
}