Pku2457 Part Acquisition

时间限制(秒)内存限制(MB)
20128

【题目描述】

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.
给出N条边,单向的。再给出数字K.问从1号点到K点号,最短路上经过多少个点。

【输入】

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.

【输出】

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).

【输入样例】

6 5
1 3
3 2
2 3
3 1
2 5
5 4

【输出样例】

4
//The cows possess 4 objects in total: first they trade object 1 for object 3, then object 3 for object 2, then object 2 for object 5.

【思路】

不专业请多见谅
这是一道求最短路径的题。我们可以建立一个dist数组,dist[i]代表1到i最短路上节点的个数。然后把dist[1]赋为1,然后循环N次,每次枚举连边规则,如果前者无值,就把后者定义为前者加1, 否则取两者中小值。最后输出dist[K]。

【源程序】

#include<iostream>
#include<cstdio>
using namespace std;
int N,K,a[50001],b[50001],dist[50001]={0};//dist[i]代表1到i的最短路上经过的点的总数 
int main()
{
    dist[1]=1;//1到1经过了一个点 
    scanf("%d%d",&N,&K);
    for(int i=1;i<=N;i++)
        scanf("%d%d",&a[i],&b[i]);
    for(int i=1;i<=N;i++)//循环N次操作 
        for(int j=1;j<=N;j++)//用j枚举N条规则
            if(dist[a[j]])//如果a[j]已经有了最短路径值 
                if(!dist[b[j]])//如果b[j]还没有被定义过
                    dist[b[j]]=dist[a[j]]+1;//a[j]到b[j]是一条边,1到b[j]的距离是1到a[j]的距离+1 
                else//如果b[j]已经被定义过 
                    dist[b[j]]=min(dist[b[j]],dist[a[j]]+1);//取两者的最小值 
    if(dist[K])//如果有最短路径 
        printf("%d",dist[K]);
    else//1走不到K点 
        printf("-1");
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值