K 站中转内最便宜的航班
有 n 个城市通过一些航班连接。给你一个数组 flights ,其中 flights[i] = [fromi, toi, pricei] ,表示该航班都从城市 fromi 开始,以价格 pricei 抵达 toi。
现在给定所有的城市和航班,以及出发城市 src 和目的地 dst,你的任务是找到出一条最多经过 k 站中转的路线,使得从 src 到 dst 的 价格最便宜 ,并返回该价格。 如果不存在这样的路线,则输出 -1。
示例 1:
输入:
n = 3, edges = [[0,1,100],[1,2,100],[0,2,500]]
src = 0, dst = 2, k = 1
输出: 200
解释:
城市航班图如下
从城市 0 到城市 2 在 1 站中转以内的最便宜价格是 200,如图中红色所示。
示例 2:
输入:
n = 3, edges = [[0,1,100],[1,2,100],[0,2,500]]
src = 0, dst = 2, k = 0
输出: 500
解释:
城市航班图如下
从城市 0 到城市 2 在 0 站中转以内的最便宜价格是 500,如图中蓝色所示。
dfs算法如下:
int findCheapestPrice(int n, int** flights, int flightsSize, int* flightsColSize, int src, int dst, int k) {int f[k + 2][n];memset(f, 0x3f, sizeof(f));f[0][src] = 0;for (int t = 1; t <= k + 1; ++t) {for (int k = 0; k < flightsSize; k++) {int j = flights[k][0], i = flights[k][1], cost = flights[k][2];f[t][i] = fmin(f[t][i], f[t - 1][j] + cost);}}int ans = 0x3f3f3f3f;for (int t = 1; t <= k + 1; ++t) {ans = fmin(ans, f[t][dst]);}return (ans == 0x3f3f3f3f ? -1 : ans);
}作者:LeetCode-Solution
链接:https://leetcode.cn/problems/cheapest-flights-within-k-stops/solution/k-zhan-zhong-zhuan-nei-zui-bian-yi-de-ha-abzi/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
动态规划算法如下:
struct node {int dst;int cost;struct node *next; };void dfs(int n,int k,struct node *N,int cp,int dst,int *s,int *num,int cost){if(n<=k){if(cp==dst){if(cost<*num){*num=cost;}}else{struct node *p=N+cp;p=p->next;while(p){if(s[p->dst]==0){printf("%d->",p->dst);s[p->dst]=1;dfs(n+1,k,N,p->dst,dst,s,num,cost+p->cost);s[p->dst]=0;}else{printf("cc");}p=p->next;}}}}
int findCheapestPrice(int n, int** flights, int flightsSize, int* flightsColSize, int src, int dst, int k){struct node *N=(struct node *)malloc(sizeof(struct node)*n);int *s=(int *)malloc(sizeof(int)*n);int *num=(int *)malloc(sizeof(int));int i;struct node *pl=N+src;*num=1000000;for(i=0;i<n;i++){(N+i)->next=NULL;s[i]=0;}s[src]=1;for(i=0;i<flightsSize;i++){struct node *p=(struct node *)malloc(sizeof(struct node)*flightsSize);p->dst=flights[i][1];p->cost=flights[i][2];p->next=(N+flights[i][0])->next;(N+flights[i][0])->next=p;}pl=pl->next;while(pl){printf("ds %d ",pl->dst);dfs(0,k,N,pl->dst,dst,s,num,pl->cost);// printf("df3");pl=pl->next;}printf("df4");if((*num)==1000000)return -1;return *num;
}