题解 P1608 【路径统计】
NieR_Automata · · 题解
这道题和P1144有异曲同工之妙 (其实都是最短路计数)
这种类型的题只需要在spfa和Dijkstra上加一个计数的数组ans[ ]就好;
实现过程
ans[x]是指从起点到x的最短路有多少条;
跑最短路在更新边长时会出现两种情况:
1.到新边x的距离比已知的距离小.
那么ans[x]就要更改(原来的ans[x]就作废了,因为它已经不是最短路了)
ans[x]=ans[a] (我们假设是从a点找到的x点,那么到x的最短路数目应该与到a点最短路数目一致)
2.到新边x的距离==已知的到x最短距离
那么我们只需要
ans[x]+=ans[a];
核心代码
if(c[x]>c[a]+edge[k].w)
ans[x]=ans[a];
else if(c[x]==c[a]+edge[k].w)
ans[x]+=ans[a];
其他
这道题里是有重边的!
我们可以开一个二维数组来记录;
另外这个数组还可以防止部分无用边;
cin>>i>>j>>w;
if(cmp[i][j]==0||cmp[i][j]>w)
{
jiantu(i,j,w);
cmp[i][j]=w;
}
【代码】
我用的是Dijkstra+堆优化(貌似不用堆优化也能过);
关于spfa(他死了)
#include <iostream>
#include <queue>
#include <vector>
#include <algorithm>
using namespace std;
typedef pair<int,int> P;
priority_queue<P , vector<P> ,greater<P> >q;
int c[2001],b[2001],ans[2001],head[3998001];
int cmp[2001][2001];
int n,m,i,j,w,cnt;
struct e{
int next,to,w;
}edge[3998001];
void jiantu(int from,int to,int w)
{
edge[++cnt].next=head[from];
edge[cnt].to=to;
edge[cnt].w=w;
head[from]=cnt;
}
void djs()
{
q.push(P(0,1));
while(!q.empty())
{
P tmp=q.top();
int a=tmp.second;
q.pop();
if(b[a]==1)continue;
b[a]=1;
for(int k=head[a];k!=0;k=edge[k].next)
{
int x=edge[k].to;
if(c[x]>c[a]+edge[k].w)
{
c[x]=c[a]+edge[k].w;
q.push(P(c[x],x));
ans[x]=ans[a];
}
else if(c[x]==c[a]+edge[k].w)
ans[x]+=ans[a];
}
}
}
int main()
{
cin>>n>>m;
fill(c+1,c+1+n,2147483647);
c[1]=0;
ans[1]=1;
for(int z=1;z<=m;z++)
{
cin>>i>>j>>w;
if(cmp[i][j]==0||cmp[i][j]>w)
{
jiantu(i,j,w);
cmp[i][j]=w;
}
}
djs();
if(c[n]==2147483647)cout<<"No answer";
else cout<<c[n]<<" "<<ans[n];
return 0;
}
最后
双倍经验!
祝各位 武运隆昌,rp++