HDU 1690 Bus System Floyd算法
http://acm.hdu.edu.cn/showproblem.php?pid=1690
题意:
第一行数据分别为L1.L2.L3.L4.C1.C2.C3.C4,和坐出租车的意思是差不多的,在行驶了0到L1距离的时候价格为C1,L1到L2之间的时候用C2 ......
第二行N和M代表在下面有N个站(坐标),M个问题。计算出一个站到另一个站所需的最少的钱。
Sample:
1 2 3 4 1 3 5 7
4 2
1
2
3
4
1 4
4 1
1到4直接不换乘的话需要5元,但在1-2,2-3,3-4这样换乘的话只用3元。
坑爹:
数据比较大,要用__int64,我把INF值直接改成了-1这样虽然多了几条语句但思路清晰一点。
这题难就那在要自己建图,给定你L1~L4,C1~C4之后把每个站之间的所需的最小费用算出来。
解法:
利用Floyd算法,初始化将每个站之间的费用算出来存入map数组中,然后利用Floyd算法进行松弛操作。
View Code
1 View Code 2 1 #include<iostream> 3 2 using namespace std; 4 3 5 4 const int maxn = 1000 + 10; 6 5 const int INF = -1; 7 6 int L1; 8 7 int L2; 9 8 int L3; 10 9 int L4; 11 10 int C1; 12 11 int C2; 13 12 int C3; 14 13 int C4; 15 14 int N; 16 15 int M; 17 16 int sta[maxn]; 18 17 __int64 map[maxn][maxn]; 19 18 20 19 void floyd() 21 20 { 22 21 int i; 23 22 int j; 24 23 int k; 25 24 for(k=0; k<=N; k++) 26 25 { 27 26 for(i=0; i<=N; i++) 28 27 { 29 28 for(j=0; j<=N; j++) 30 29 { 31 30 if(map[i][k] != INF && map[k][j] != INF) 32 31 { 33 32 if(map[i][j] > map[i][k] + map[k][j] || map[i][j] == INF) 34 33 { 35 34 map[i][j] = map[i][k] + map[k][j]; 36 35 } 37 36 } 38 37 } 39 38 } 40 39 } 41 40 } 42 41 43 42 __int64 km(int a,int b) 44 43 { 45 44 int price; 46 45 price = abs(sta[a]-sta[b]); 47 46 if(price>0 && price<=L1) 48 47 { 49 48 return C1; 50 49 } 51 50 if(price>L1 && price<=L2) 52 51 { 53 52 return C2; 54 53 } 55 54 if(price>L2 && price<=L3) 56 55 { 57 56 return C3; 58 57 } 59 58 if(price>L3 && price<=L4) 60 59 { 61 60 return C4; 62 61 } 63 62 return INF; 64 63 } 65 64 66 65 67 66 68 67 69 68 void init() 70 69 { 71 70 int i; 72 71 int j; 73 72 memset(map,INF,sizeof(map)); 74 73 for(i=1; i<=N; i++) 75 74 { 76 75 for(j=i+1; j<=N; j++) 77 76 { 78 77 __int64 price; 79 78 price=km(i,j); 80 79 map[i][j]=price; 81 80 map[j][i]=price; 82 81 } 83 82 } 84 83 } 85 84 86 85 87 86 int main() 88 87 { 89 88 int T; 90 89 cin>>T; 91 90 int k=1; 92 91 while(T--) 93 92 { 94 93 cin>>L1>>L2>>L3>>L4>>C1>>C2>>C3>>C4; 95 94 cin>>N>>M; 96 95 int i; 97 96 for(i=1; i<=N; i++) 98 97 { 99 98 cin>>sta[i]; 100 99 } 101 100 102 101 init(); 103 102 floyd(); 104 103 105 104 cout<<"Case "<<k++<<":"<<endl; 106 105 107 106 for(i=0; i<M; i++) 108 107 { 109 108 int x; 110 109 int y; 111 110 cin>>x>>y; 112 111 if(map[x][y]!=INF) 113 112 { 114 113 cout<<"The minimum cost between station "<<x<<" and station "<<y<<" is "; 115 114 printf("%I64d",map[x][y]); 116 115 cout<<"."<<endl; 117 116 } 118 117 else 119 118 { 120 119 cout<<"Station "<<x<<" and station "<<y<<" are not attainable."<<endl; 121 120 } 122 121 } 123 122 } 124 123 return 0; 125 124 }