bzoj 1674: [Usaco2005]Part Acquisition(最短路)

来源:互联网 发布:大数据公司有哪些设备 编辑:程序博客网 时间:2024/06/05 18:28

1674: [Usaco2005]Part Acquisition

Time Limit: 5 Sec  Memory Limit: 64 MB
Submit: 444  Solved: 219
[Submit][Status][Discuss]

Description

The cows have been sent on a mission through space to acquire a new milking machine for their barn. They are flying through a cluster of stars containing N (1 <= N <= 50,000) planets, each with a trading post. The cows have determined which of K (1 <= K <= 1,000) types of objects (numbered 1..K) each planet in the cluster desires, and which products they have to trade. No planet has developed currency, so they work under the barter system: all trades consist of each party trading exactly one object (presumably of different types). The cows start from Earth with a canister of high quality hay (item 1), and they desire a new milking machine (item K). Help them find the best way to make a series of trades at the planets in the cluster to get item K. If this task is impossible, output -1.

Input

* Line 1: Two space-separated integers, N and K. * Lines 2..N+1: Line i+1 contains two space-separated integers, a_i and b_i respectively, that are planet i's trading trading products. The planet will give item b_i in order to receive item a_i.

Output

* Line 1: One more than the minimum number of trades to get the milking machine which is item K (or -1 if the cows cannot obtain item K).

Sample Input

6 5 //6个星球,希望得到5,开始时你手中有1号货物.
1 3 //1号星球,希望得到1号货物,将给你3号货物
3 2
2 3
3 1
2 5
5 4

Sample Output

4


题意:

第一行输入两个数n和k表示有n个星球,你想要k号机器,而你一开始手上只有1号机器

接下来n行,每行两个数ai, bi表示第i个星球愿意拿bi号机器换ai号机器

问你最少需要换少次才能换到你想要的k号机器?

如果能换到输出这个答案+1,否则输出-1


每号机器当成一个点,每个ai和bi连一条ai到bi的有向边

求出1到k的最短路即可

#include<stdio.h>#include<string.h>#include<algorithm>#include<queue>using namespace std;int bet[1005], len[52005];int cnt, node[52005], nxt[52005], head[1005];void Add(int x, int y, int z){node[++cnt] = y;nxt[cnt] = head[x];head[x] = cnt;len[cnt] = z;}void Dij(){int i, v, now;memset(bet, 10, sizeof(bet));bet[1] = 0;priority_queue<pair<int, int> > q;q.push(make_pair(0, 1));while(1){while(q.empty()==0 && -bet[q.top().second]<q.top().first)q.pop();if(q.empty())break;now = q.top().second;q.pop();for(i=head[now];i;i=nxt[i]){v = node[i];if(bet[v]>bet[now]+len[i]){bet[v] = bet[now]+len[i];q.push(make_pair(-bet[v], v));}}}}int main(void){int i, n, T, x, y;scanf("%d%d", &n, &T);memset(head, 0, sizeof(head));for(i=1;i<=n;i++){scanf("%d%d", &x, &y);Add(x, y, 1);}Dij();if(bet[T]<=n)printf("%d\n", bet[T]+1);elseprintf("-1\n");return 0;}


原创粉丝点击