前言
这是今天C组的题,闲得无聊做了一会,结果就对了233。这算是学了SPFA之后的第一次实战了。反正其他C组题我也不想做了。好了现在bi~~(系统自动屏蔽)也在做这道题。
还有这道题的名字叫
正题
题目
一个有向图,有两个GPS,它们认为每条边的长度不尽相同,如果你走的路有GPS认为这不是最短路,就会报警警告一次,如果两个GPS都认为不是,那就会警告2次,要求警告次数最少。
Input
第一行,整数N 和M。
接下来M 行,第i 行有四个整数Ai,Bi, Pi,Qi 描述第i 条道路。
Output
输出单独一行一个整数——FJ 选择从他家到达农场的最佳线路之后,路上收到的最小总警告数。
Sample Input
5 7
3 4 7 1
1 3 2 20
1 4 17 18
4 5 25 3
1 2 10 1
3 5 4 14
2 4 6 5
Sample Output
1
【样例解释】
输入详述:
这里有5 个路口和7 条有向道路。第一条道路从路口3 到路口4 连接两个路口;第一GPS 认为这条路需要7 单位时间来通过,接着第二GPS 认为它只需1单位时间,诸如此类。
输出详述:
如果FJ 按照路线1->2->4->5 走,那么第一GPS 会在1->2 这条路上发出警告(它认为1->3 这条路更好)。然而,对于路线剩下的2->4->5,两个GPS 都快乐地坐着FJ 的小车通过了,因为每个GPS 都以为这是2 到5 的最短路。
解题思路
首先我们要分别算出2个GPS的每个点到达终点的最小值,然后判断如果前一个点的最短路+两点之间的权值不等于后一个点的最短路,则这个GPS会认为这条路是错的。为了方便我们把有向图倒着存,然后SPFA搜3次。
代码
#include<cstdio>
#include<cstring>
using namespace std;
struct line{
int first,last,l1,l2,next;
};//邻接表
line a[50001];
int f[10001],f2[10001],ff[10001],n,m,ls[10001],state[10001],tail,head,p,w;
bool b[10001];
void spfaA()
{
memset(f,127/3,sizeof(f));//初始化
tail=1;head=0;f[n]=0;
state[1]=n;b[n]=true;//初始化
do
{
head=(head+2)%n-1;//循环队列
p=ls[state[head]];//找边
while (p!=0)
{
if (f[a[p].first]+a[p].l1<f[a[p].last])//松弛
{
f[a[p].last]=f[a[p].first]+a[p].l1;
if (!b[a[p].last])
{
tail=(tail+2)%n-1;//入队
state[tail]=a[p].last;
b[a[p].last]=true;
}
}
p=a[p].next;//下一条
}
b[state[head]]=false;//解封
}
while (tail!=head);
}
void spfaB()//一样的不解释
{
memset(f2,127/3,sizeof(f2));
tail=1;head=0;f2[n]=0;
state[1]=n;b[n]=true;
do
{
head=(head+2)%n-1;
p=ls[state[head]];
while (p!=0)
{
if (f2[a[p].first]+a[p].l2<f2[a[p].last])
{
f2[a[p].last]=f2[a[p].first]+a[p].l2;
if (!b[a[p].last])
{
tail=(tail+2)%n-1;
state[tail]=a[p].last;
b[a[p].last]=true;
}
}
p=a[p].next;
}
b[state[head]]=false;
}
while (tail!=head);
}
int check(int x)//判断该条边会有几个GPS报错
{
int s=0;
if (f[a[x].first]+a[x].l1!=f[a[x].last]) s++;//第一个GPS
if (f2[a[x].first]+a[x].l2!=f2[a[x].last]) s++;//第二个GPS
return s;//返回
}
void spfa()
{
memset(ff,127/3,sizeof(ff));
tail=1;head=0;ff[n]=0;
state[1]=n;b[n]=true;
do
{
head=(head+2)%n-1;
p=ls[state[head]];
while (p!=0)
{
w=check(p);//代价
if (ff[a[p].first]+w<ff[a[p].last])
{
ff[a[p].last]=ff[a[p].first]+w;
if (!b[a[p].last])
{
tail=(tail+2)%n-1;
state[tail]=a[p].last;
b[a[p].last]=true;
}
}
p=a[p].next;
}
b[state[head]]=false;
}
while (tail!=head);
printf("%d",ff[1]);//输出
}
int main()
{
freopen("gpsdual.in","r",stdin);
freopen("gpsdual.out","w",stdout);
scanf("%d%d",&n,&m);
for (int i=1;i<=m;i++)
{
scanf("%d%d%d%d",&a[i].last,&a[i].first,&a[i].l1,&a[i].l2);
a[i].next=ls[a[i].first];
ls[a[i].first]=i;
}
spfaA();
spfaB();
spfa();
}
好了现在bi~~(系统自动屏蔽)做完了道题。