洛谷 P2483 [SDOI2010]魔法猪学院

P2483 [SDOI2010]魔法猪学院

k短路模板

  1 #include<queue>
  2 #include<cstdio>
  3 #include<cstring>
  4 #include<algorithm>
  5 using namespace std;
  6 const int maxn=10005;
  7 int n,m,s,t,k,num,head1[maxn*100],head2[maxn*100],tot;
  8 int nxt1[maxn*100],nxt2[maxn*100],cnt;
  9 double dis[maxn*100],e;
 10 queue<int>q; bool vis[maxn];
 11 struct Edge{
 12     int u,v;
 13     double d;
 14 }edge1[maxn*100],edge2[maxn*100];
 15 
 16 struct Data{
 17     int num;
 18     double h,g;
 19     bool operator < (const Data x) const
 20     {
 21         if(h==x.h) return g>x.g;
 22         return h>x.h;
 23     }
 24 };
 25 
 26 char ch;
 27 inline void read(int &now)
 28 {
 29     ch=getchar(); now=0;
 30     while(ch>'9'||ch<'0') ch=getchar();
 31     while(ch>='0'&&ch<='9') now=now*10+ch-'0',ch=getchar();
 32 }
 33 
 34 void add_Edge(int u,int v,double d)
 35 {
 36     edge2[++num].u=u;
 37     edge2[num].v=v;
 38     edge2[num].d=d;
 39     nxt2[num]=head2[u];
 40     edge1[num].u=v;
 41     edge1[num].v=u;
 42     edge1[num].d=d;
 43     nxt1[num]=head1[v];
 44     head2[u]=num;
 45     head1[v]=num;
 46 }
 47 
 48 void spfa()
 49 {
 50     for(int i=0;i<=n;i++) dis[i]=0x7f;
 51     dis[t]=0;
 52     vis[t]=1;
 53     q.push(t);
 54     while(!q.empty())
 55     {
 56         int cur=q.front(); q.pop();
 57         for(int i=head2[cur];i;i=nxt2[i])
 58         {
 59             int v=edge2[i].v;
 60             if(dis[v]>dis[cur]+edge2[i].d)
 61             {
 62                 dis[v]=dis[cur]+edge2[i].d;
 63                 if(!vis[v])
 64                 {
 65                     vis[v]=1;
 66                     q.push(v);
 67                 }
 68             }
 69         }
 70         vis[cur]=0;
 71     }
 72 }
 73 
 74 int astar()
 75 {
 76     priority_queue<Data>que;
 77     Data u,v,w;
 78     u.num=s;
 79     u.g=0;
 80     u.h=dis[s];
 81     que.push(u);
 82     while(!que.empty())
 83     {
 84         v=que.top(); que.pop();
 85         if(v.num==t) 
 86         {
 87             e-=v.g;
 88             if(e>=0) tot++;
 89             else return tot;
 90         }
 91         for(int i=head1[v.num];i;i=nxt1[i])
 92         {
 93             w.num=edge1[i].v;
 94             w.g=v.g+edge1[i].d;
 95             w.h=w.g+dis[edge1[i].v];
 96             que.push(w);
 97         }
 98     }
 99 }
100 
101 int main()
102 {
103     read(n); read(m); scanf("%lf",&e);
104     for(int i=1;i<=m;i++)
105     {
106         int x,y; double z;
107         read(x); read(y); scanf("%lf",&z);
108         add_Edge(y,x,z);
109     }
110     s=1; t=n;
111     spfa();
112     printf("%d
",astar());
113     return 0;
114 }
View Code
原文地址:https://www.cnblogs.com/chen74123/p/7476109.html