USACO09FEB 改造路Revamping Trails(分层图模板)

满分做法:

因为\(k\)很小,所以把每个点拆出\(k\)个点,对应使了多少个高速,这个就是分层图了。

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<queue>
#include<cmath>
using namespace std;
typedef long long ll;
const int maxm=3000007;
int n,m,k;
int pre[maxm<<1],last[maxm],len[maxm<<1],other[maxm<<1],l;
ll dis[maxm];
bool vis[maxm];
priority_queue<pair<ll,int> >q;
ll ans;
void add(int x,int y,int z)
{
 l++;
 pre[l]=last[x];
 last[x]=l;
 other[l]=y;    
 len[l]=z;
}
void dijkstra()
{
 for(int i=1;i<=(k+1)*n;i++)
 dis[i]=1e14+7;
 dis[1]=0;
 q.push(make_pair(0,1));
 while(q.size())
 {
  int u=q.top().second;
  q.pop();
  if(vis[u]) continue;
  vis[u]=1;
  for(int p=last[u];p;p=pre[p])
  {
   int v=other[p];
   if(dis[v]>dis[u]+len[p])
   {
     dis[v]=dis[u]+len[p];
     q.push(make_pair(-dis[v],v));
   }   
  }
 }  
}
int main()
{
 scanf("%d%d%d",&n,&m,&k);
 for(int i=1;i<=m;i++)
 {
   int x,y,z;
   scanf("%d%d%d",&x,&y,&z);
   add(x,y,z);
   add(y,x,z);
   for(int j=1;j<=k;j++)
   {
     add(j*n+x,j*n+y,z);
     add(j*n+y,j*n+x,z);
     add((j-1)*n+x,j*n+y,0);
     add((j-1)*n+y,j*n+x,0);
   }
 }
 dijkstra();
 ans=dis[n];
 for(int j=1;j<=k;j++)
 {
   ans=min(ans,dis[j*n+n]);
 }
 printf("%lld\n",ans);
 return 0;  
}

猜你喜欢

转载自www.cnblogs.com/lihan123/p/11832712.html