题目链接:http://acm.uestc.edu.cn/problem.php?pid=1558&cid=129
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).
解题思路:
由于题目数据量很大,点的个数达到了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; }