题目描述
这一晚,TT 做了个美梦!
在梦中,TT 的愿望成真了,他成为了喵星的统领!喵星上有 N 个商业城市,编号 1 ~ N,其中 1 号城市是 TT 所在的城市,即首都。
喵星上共有 M 条有向道路供商业城市相互往来。但是随着喵星商业的日渐繁荣,有些道路变得非常拥挤。正在 TT 为之苦恼之时,他的魔法小猫咪提出了一个解决方案!TT 欣然接受并针对该方案颁布了一项新的政策。
具体政策如下:对每一个商业城市标记一个正整数,表示其繁荣程度,当每一只喵沿道路从一个商业城市走到另一个商业城市时,TT 都会收取它们(目的地繁荣程度 - 出发地繁荣程度)^ 3 的税。
TT 打算测试一下这项政策是否合理,因此他想知道从首都出发,走到其他城市至少要交多少的税,如果总金额小于 3 或者无法到达请悄咪咪地打出 ‘?’。
Input
第一行输入 T,表明共有 T 组数据。(1 <= T <= 50)
对于每一组数据,第一行输入 N,表示点的个数。(1 <= N <= 200)
第二行输入 N 个整数,表示 1 ~ N 点的权值 a[i]。(0 <= a[i] <= 20)
第三行输入 M,表示有向道路的条数。(0 <= M <= 100000)
接下来 M 行,每行有两个整数 A B,表示存在一条 A 到 B 的有向道路。
接下来给出一个整数 Q,表示询问个数。(0 <= Q <= 100000)
每一次询问给出一个 P,表示求 1 号点到 P 号点的最少税费。
Output
每个询问输出一行,如果不可达或税费小于 3 则输出 ‘?’。
Sample Input
2
5
6 7 8 9 10
6
1 2
2 3
3 4
1 5
5 4
4 5
2
4
5
10
1 2 4 4 5 6 7 8 9 10
10
1 2
2 3
3 1
1 4
4 5
5 6
6 7
7 8
8 9
9 10
2
3 10
Sample Output
Case 1:
3
4
Case 2:
?
?
思路
题目要求1到其他点需要花费最少的钱,相当于从1向其他点求最短路。但问题在于两点之间的距离权值有负值存在,如果图中存在负环,则被负环影响的点与源点之间的距离变为了无穷小,最短路计算时可能会在负环中陷入无限循环,因此需要对点是否进入负环进行判断。利用spfa算法从1号城市开始搜索,如果发现到达某一个城市经过的边数超过n-1,那就说明出现了负环,则从此点开始搜索被负环影响的点,到达的点都打上标记。
代码
#include <iostream>
#include <queue>
#include <string.h>
#include <cmath>
using namespace std;
const int M = 1e6 + 10;
const int inf = 1e9;
const int N = 200 + 10;
struct Edge {
int to, next, w;
}e[M];
int vis[N], cnt[N], dis[N], head[N], temp[N];
int n, m, tot, t, a, b, r;
bool flag[N];
void add(int x, int y,int z)
{
e[++tot].to = y;
e[tot].w = z;
e[tot].next = head[x];
head[x] = tot;
}
void dfs(int s)
{
flag[s] = true;
for (int i = head[s]; i; i = e[i].next)
{
int u = e[i].to;
if (!flag[u])
{
dfs(u);
}
}
}
queue<int> q;
void spfa(int s)
{
while (q.size())
q.pop();
for (int i = 1; i <= n; i++)
vis[i] = cnt[i] = 0, dis[i] = inf, flag[i] = false;
dis[s] = 0, vis[s] = 1;
q.push(s);
while (q.size())
{
int x = q.front();
q.pop();
vis[x] = 0;
for (int i = head[x]; i; i = e[i].next)
{
int y = e[i].to;
if (dis[y] > dis[x] + e[i].w)
{
cnt[y] = cnt[x] + 1;
if (cnt[y] >= n)
{
dfs(y);
}
dis[y] = dis[x] + e[i].w;
if (vis[y]==0&&!flag[y])
vis[y] = 1, q.push(y);
}
}
}
}
int main()
{
scanf("%d", &t);
for (int tt = 1; tt <= t; tt++)
{
tot = 0;
memset(temp, 0, sizeof(temp));
memset(head, 0, sizeof(head));
scanf("%d", &n);
for (int i = 1; i <= n; i++)
scanf("%d", &temp[i]);
scanf("%d", &m);
for (int i = 1; i <= m; i++)
{
scanf("%d %d", &a, &b);
int c = pow((temp[b] - temp[a]), 3);
add(a, b, c);
}
spfa(1);
printf("Case %d:\n", tt);
scanf("%d", &r);
for (int i = 1; i <= r; i++)
{
int p;
scanf("%d", &p);
if (flag[p] || dis[p] < 3 || dis[p] == inf)
printf("?\n");
else
printf("%d\n", dis[p]);
}
}
return 0;
}