题目链接:http://acm.uestc.edu.cn/problem.php?pid=1558&cid=129
In each exchange, one can exchange for an item of Vi yuan if he (she) has an item values more than or equal to Ri yuan, with a time cost of Ti minutes.
Now, you task is help the star to exchange for an item which values more than or equal to M yuan with the minimum time.
The first line of the input is T (no more than 20), which stands for the number of test cases you need to solve.
For each case, two integers N, M (1 <= N <= 10^5, 1 <= M <= 10^9) in the first line indicates the number of available exchanges and the expected value of final item. Then N lines follow, each line describes an exchange with 3 integers Vi, Ri, Ti (1 <= Ri <= Vi <= 10^9, 1 <= Ti <= 10^9).
For every test case, you should output "Case #k: " first, where k indicates the case number and counts from 1. Then output the minimum time. Output “-1” if no solution can be found.
3 10
5 1 3
8 2 5
10 9 2
4 5
2 1 1
3 2 1
4 3 1
8 4 1
5 9
5 1 1
10 4 10
8 1 10
11 6 1
7 3 8
Case #2: 4
Case #3: 10
解题思路:
由于题目数据量很大,点的个数达到了10^5,所以普通的图论最短路方法是要超时的。
所以我想到了BFS,但是这个题目,如果仅仅使用BFS的话还是会超时的。
于是我们可以更进一步优化,变为优先队列+BFS
我们可以先对所有的边按起点(初始金额)排序。
然后优先队列我们用每一条边的交换时间来作为优先条件。
我的代码:
#include<stdio.h> #include<queue> #include<algorithm> using namespace std; struct edge { long long v; long long u; long long t; }; struct node { long long money; long long t; friend bool operator<(node a,node b) { return a.t>b.t; } }; edge e[100005]; long long num,m; bool cmp(edge a,edge b) { return a.u<b.u; } long long bfs() { node k1,k2; long long i,left=1; priority_queue<node>q; k1.money=1; k1.t=0; q.push(k1); while(!q.empty()) { k2=q.top(); q.pop(); if(k2.money>=m) return k2.t; for(i=left;i<=num;i++) { if(k2.money>=e[i].u&&e[i].v>k2.money) { k1.money=e[i].v; k1.t=k2.t+e[i].t; q.push(k1); } if(k2.money<e[i].u) break; } left=i; } return -1; } int main() { long long n,i,t,T,ans; long long a,b,c; scanf("%lld",&T); for(t=1;t<=T;t++) { num=0; scanf("%lld%lld",&n,&m); for(i=1;i<=n;i++) { scanf("%lld%lld%lld",&a,&b,&c); if(a==b) continue; num++; e[num].u=b; e[num].v=a; e[num].t=c; } sort(e+1,e+1+num,cmp); ans=bfs(); printf("Case #%lld: %lld\n",t,ans); } return 0; }
本文探讨了一个在慈善交换节目中帮助明星通过优化BFS算法以最小化时间找到价值不低于目标金额物品的方法。详细介绍了如何通过排序边并使用优先队列优化搜索过程,最终在多个测试案例中有效求解。
2038

被折叠的 条评论
为什么被折叠?



