题意
给出n个点的有向带边权的图。求最多有几条不同的从1到n的路径,使这些路径长度加和小于等于给定的一个值allw。
题解
显然选的路径是前k短路。
对于前k短路的问题,我们可以用A∗来优化暴力搜索。
我们知道,当A∗的估价函数h(x)=实际需要的代价时,每一步都是最优的。这里实际上我们是可以做到这一点的,用反向建图的技巧即可求出每个点到终点n的实际距离,并把它作为h(x)。显然如果不干掉访问的节点,A∗ 前k次到达终点即对应前k短路。
A*什么时候停止呢?可以在一开始估算一下K可能的最大值,这样每个节点最多入队k次。(这里我的代码没有体现,稍微有点乱,但差别不大)
由于存在完美的估计函数,程序效率就很不错了。
听说这题STL卡空间?好像没有发生什么…
#include<cstdio>
#include<queue>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=5005,maxe=200005;
const double eps=1e-7;
int fir[2][maxn],son[2][maxe],nxt[2][maxe],tot[2];
int n,m,ans,vis[maxn];
double allw,w[2][maxe],f[maxn];
void add(int k,int x,int y,double z){
son[k][++tot[k]]=y; w[k][tot[k]]=z; nxt[k][tot[k]]=fir[k][x]; fir[k][x]=tot[k];
}
queue<int> que;
void spfa(){
for(int i=1;i<=n;i++) f[i]=1e+50;
f[n]=0; que.push(n);
while(!que.empty()){
int x=que.front(); que.pop(); vis[x]=false;
for(int j=fir[1][x];j;j=nxt[1][j]) if(f[x]+w[1][j]<f[son[1][j]]){
f[son[1][j]]=f[x]+w[1][j];
vis[son[1][j]]=true; que.push(son[1][j]);
}
}
}
struct data{
int x; double g;
data(int x1=0,double x2=0):x(x1),g(x2){}
bool operator < (const data &b)const{
return g+f[x]>b.g+f[b.x];
}
};
priority_queue<data> _heap;
int cnt[maxn];
void A_star(){
_heap.push(data(1,0));
while(!_heap.empty()){
data now=_heap.top(); _heap.pop();
if(now.g+f[now.x]-eps>allw) break;
if(now.x==n){ ans++; allw-=now.g; continue; }
for(int j=fir[0][now.x];j;j=nxt[0][j]) if(now.g+w[0][j]+f[son[0][j]]<=allw){
_heap.push(data(son[0][j],now.g+w[0][j]));
}
}
}
int main(){
freopen("bzoj1975.in","r",stdin);
freopen("bzoj1975.out","w",stdout);
scanf("%d%d%lf",&n,&m,&allw);
for(int i=1;i<=m;i++){
int x,y; double z; scanf("%d%d%lf",&x,&y,&z);
add(0,x,y,z); add(1,y,x,z);
}
spfa();
A_star();
printf("%d\n",ans);
return 0;
}