一、题目描述
这一晚,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.题目大致意思就是,给出了N个点和他们的权值,再告诉我们M条有向道路,路径长度可由权值算出。然后求出1号点到其他任何一个点的距离。
2.由于路径的长度有可能是负值,所以负环的存在是有可能的,可使用SPFA方法来解题。
3.当前点为s,则松弛所有与s邻接的点,再松弛与s邻接的点…
如果当前点被松弛了N+1次,那么就说明有负环,标记这些在负环里的点,这些点不用再松弛。
三、完整代码
#include<bits/stdc++.h>
const int maxn= 200010;
const int inf = 100000000;
using namespace std;
//前向星
struct edge
{
int to, next, w;
}e[2*maxn];
int tol=0;
int head[maxn],dis[maxn],pre[maxn],inq[maxn],cnt[maxn],vis[maxn];
void init()
{
tol = 0;
for (int i = 0; i < maxn; i++)
head[i] = -1;
}
void addedge(int form,int to, int w)
{
tol++;//从e[1]开始存储数据
e[tol].to = to;
e[tol].w = w;
e[tol].next = head[form];
head[form] = tol;
}
void dfs(int x)
{
for(int i=head[x]; i!=0; i=e[i].next){
int t = e[i].to;
if(!vis[t])
{
vis[t] = 1;
dfs(t);
}
}
}
void spfa(int n)
{
for(int i=1;i<=n;i++)
{
dis[i]=inf;
vis[i]=0;
pre[i]=0;
inq[i]=0;
cnt[i]=0;
}
dis[1]=0;
queue<int>q;
q.push(1);
while(!q.empty())
{
int u=q.front();
q.pop();
inq[u]=0;
for(int i = head[u]; i!=0; i = e[i].next)
{
int w=e[i].w;
if(vis[v])continue;
if(dis[v]>dis[u]+w)
{
cnt[v]=cnt[u]+1;
if(cnt[v]>=n)
{
//找到负环
vis[v] = 1;
dfs(v);
}
dis[v]=dis[u]+w;
pre[v]=u;
if(!inq[v])
{
q.push(v);
inq[v]=1;
}
}
}
}
}
int main()
{
int T;
scanf("%d",&T);//T组数据
for(int j=0;j<T;j++)
{
init();
int N;
scanf("%d",&N);//表示点的个数
int *a=new int[N+1];
for(int i=1;i<=N;i++)
scanf("%d",&a[i]);//表示 1 ~ N 点的权值
int M;//表示有向道路的条数
scanf("%d",&M);
for(int i=0;i<M;i++)
{
int A,B;
scanf("%d%d",&A,&B);
int w=a[B]-a[A];
addedge(A,B,w*w*w);
}
spfa(N);
int Q;
scanf("%d",&Q);
cout<<"Case "<<j+1<<":"<<endl;
for(int i=0;i<Q;i++)
{
int P;
scanf("%d",&P);
if(vis[P] || dis[P]==inf || dis[P]<3)
cout<<"?"<<endl;
else
cout<<dis[P]<<endl;
}
}
}