HDU4396
题意:s到e,最短时间且至少经过k条边
dis[ i ][ j ]:表示s到i至少经过了j条边的最少时间!
二维spfa
View Code
1 #include<stdio.h> 2 #include<string.h> 3 #include<queue> 4 #include<algorithm> 5 #include<stdlib.h> 6 using namespace std; 7 const int maxn = 5005; 8 const int maxm = 100005; 9 const int inf = 9999999; 10 int n,m; 11 int ans; 12 struct node{ 13 int u,val,next; 14 }edge[ maxm*2 ]; 15 int head[ maxn ],cnt; 16 void init(){ 17 cnt=0; 18 memset( head,-1,sizeof( head )); 19 } 20 void addedge( int a,int b,int c ){ 21 edge[ cnt ].u=b; 22 edge[ cnt ].val=c; 23 edge[ cnt ].next=head[ a ]; 24 head[ a ]=cnt++; 25 } 26 int dis[ maxn ][ 505 ],vis[ maxn ][ 505 ];//dis[i][j]:s到i经过j步的最少时间 27 struct node2{ 28 int pos,num; 29 }; 30 31 32 void spfa( int s,int e,int k ){ 33 memset( vis,0,sizeof( vis ) ); 34 //memset( dis,0x3f3f3f,sizeof( dis )); 35 for(int i=1;i<=n;i++) 36 for(int j=0;j<=k;j++) 37 dis[i][j]=inf; 38 queue<node2>q; 39 while(!q.empty())q.pop(); 40 node2 now,next; 41 now.pos=s,now.num=0; 42 vis[ now.pos ][ now.num ]=1; 43 dis[ now.pos ][ now.num ]=0; 44 q.push( now ); 45 ans=inf; 46 while( !q.empty() ){ 47 now=q.front(),q.pop(); 48 vis[now.pos][now.num]=0; 49 if( now.pos==e&&now.num==k ){ 50 ans=min( ans,dis[e][k] );//return dis[e][k]; 51 } 52 for( int i=head[ now.pos ];i!=-1;i=edge[i].next ){ 53 next.pos=edge[i].u; 54 next.num=now.num+10; 55 if(next.num>=k)next.num=k; 56 if( next.num>=k ) 57 next.num=k; 58 if( dis[next.pos][next.num]>dis[now.pos][now.num]+edge[i].val ){ 59 dis[next.pos][next.num]=dis[now.pos][now.num]+edge[i].val; 60 if( vis[next.pos][next.num]==0 ){ 61 vis[next.pos][next.num]=1; 62 q.push(next); 63 } 64 } 65 } 66 } 67 if( ans==inf ) 68 ans=-1; 69 } 70 71 int main(){ 72 while( scanf("%d%d",&n,&m)!=EOF ){ 73 init(); 74 int a,b,c; 75 while( m-- ){ 76 scanf("%d%d%d",&a,&b,&c); 77 addedge( a,b,c ); 78 addedge( b,a,c ); 79 } 80 int s,e,k; 81 scanf("%d%d%d",&s,&e,&k); 82 spfa( s,e,k ); 83 printf("%d\n",ans); 84 } 85 return 0; 86 }
keep moving...