题目链接:
https://www.lydsy.com/JudgeOnline/problem.php?id=2763
题目大意:
Alice和Bob现在要乘飞机旅行,他们选择了一家相对便宜的航空公司。该航空公司一共在n个城市设有业务,设这些城市分别标记为0到n-1,一共有m种航线,每种航线连接两个城市,并且航线有一定的价格。Alice和Bob现在要从一个城市沿着航线到达另一个城市,途中可以进行转机。航空公司对他们这次旅行也推出优惠,他们可以免费在最多k种航线上搭乘飞机。那么Alice和Bob这次出行最少花费多少?
思路:
BFS分层即可。
1 #include<bits/stdc++.h> 2 #define IOS ios::sync_with_stdio(false);//不可再使用scanf printf 3 #define Max(a, b) ((a) > (b) ? (a) : (b))//禁用于函数,会超时 4 #define Min(a, b) ((a) < (b) ? (a) : (b)) 5 #define Mem(a) memset(a, 0, sizeof(a)) 6 #define Dis(x, y, x1, y1) ((x - x1) * (x - x1) + (y - y1) * (y - y1)) 7 #define MID(l, r) ((l) + ((r) - (l)) / 2) 8 #define lson ((o)<<1) 9 #define rson ((o)<<1|1) 10 #define Accepted 0 11 #pragma comment(linker, "/STACK:102400000,102400000")//栈外挂 12 using namespace std; 13 inline int read() 14 { 15 int x=0,f=1;char ch=getchar(); 16 while (ch<'0'||ch>'9'){if (ch=='-') f=-1;ch=getchar();} 17 while (ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();} 18 return x*f; 19 } 20 typedef long long ll; 21 const int maxn = 100000 + 10; 22 const int MOD = 1000000007;//const引用更快,宏定义也更快 23 const int INF = 1e9 + 7; 24 const double eps = 1e-6; 25 bool vis[maxn][11]; 26 struct edge 27 { 28 int v, w; 29 edge(){} 30 edge(int v, int w):v(v), w(w){} 31 }; 32 vector<edge>G[maxn]; 33 int n, m, k; 34 int s, t; 35 struct Heapnode 36 { 37 int d, id, k;//距离 点 层数 38 Heapnode(){} 39 Heapnode(int d, int id, int k):d(d), id(id), k(k){} 40 bool operator< (const Heapnode & a)const 41 { 42 return d > a.d || d == a.d && k > a.k; 43 } 44 }; 45 priority_queue<Heapnode>q; 46 int BFS() 47 { 48 q.push(Heapnode(0, s, 0)); 49 while(!q.empty()) 50 { 51 Heapnode now = q.top(); 52 q.pop(); 53 if(vis[now.id][now.k])continue; 54 vis[now.id][now.k] = 1; 55 if(now.id == t) 56 { 57 return now.d; 58 } 59 for(int i = 0; i < G[now.id].size(); i++) 60 { 61 int v = G[now.id][i].v; 62 int w = G[now.id][i].w; 63 if(!vis[v][now.k]) 64 { 65 q.push(Heapnode(now.d + w, v, now.k)); 66 } 67 if(!vis[v][now.k + 1] && now.k + 1 <= k) 68 { 69 q.push(Heapnode(now.d, v, now.k + 1)); 70 } 71 } 72 } 73 } 74 int main() 75 { 76 scanf("%d%d%d", &n, &m, &k); 77 scanf("%d%d", &s, &t); 78 while(m--) 79 { 80 int u, v, w; 81 scanf("%d%d%d", &u, &v, &w); 82 G[u].push_back(edge(v, w)); 83 G[v].push_back(edge(u, w)); 84 } 85 printf("%d ", BFS()); 86 return Accepted; 87 }