FOJ 1436 Renting Boats

 

http://acm.fzu.edu.cn/problem.php?pid=1436

 

题目大意:这道题的意思就是说,一条江上游N个租船点,从一个租船点到另一个租船点都有一个租船费,并且每个租船点都只能前往编号比它大的租船点,这个费用题目已经给你了。问你现在从1这个租船点到最后一个N这个租船点最少的租金。

 

解题思路:这道题就是求最短路径的问题啦,用Prim算法或者是Dijkstra算法都可以做,不过Dijkstra算法的时间复杂度更低,所以建议用Dijkstra算法做.

#include <stdio.h> #include <string.h> #define Size 205 #define INIT 999999 int Graph[Size][Size]; void Dijkstra(int NumOfBoats,int lowcost[]) { int i,j; int min; int locate; bool visited[Size]; memset(visited,0,sizeof(visited)); for (i=1;i<=NumOfBoats;i++) lowcost[i] = Graph[1][i]; for (j=2;j<=NumOfBoats;j++) { min = INIT; for (i=2;i<=NumOfBoats;i++) { if (!visited[i]&&lowcost[i]<min) { min = lowcost[i]; locate = i; } } visited[locate] = true; for (i=2;i<=NumOfBoats;i++) { if (!visited[i]) { if(lowcost[i]>Graph[locate][i]+lowcost[locate]) lowcost[i] = Graph[locate][i]+lowcost[locate]; } } } } int main() { int NumOfBoats; int i,j; int lowcost[Size]; while (scanf("%d",&NumOfBoats)!=EOF) { memset(Graph,0,sizeof(Graph)); for (i=1;i<=NumOfBoats;i++) { for (j=1;j<=NumOfBoats;j++) { if (i==j) Graph[i][j] = 0; else Graph[i][j] = INIT; } } memset(lowcost,0,sizeof(lowcost)); for (i=1;i<NumOfBoats;i++) for (j=i+1;j<=NumOfBoats;j++) scanf("%d",&Graph[i][j]); Dijkstra(NumOfBoats,lowcost); printf("%d/n",lowcost[NumOfBoats]); } return 0; }   

 

 

你可能感兴趣的:(算法,Graph)