Problem L: Pku2457 Part Acquisition

Problem L: Pku2457 Part Acquisition

Description
给出N条边,单向的。再给出数字K.问从1号点到K点号,最短路上经过多少个点。

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
1 3
3 2
2 3
3 1
2 5
5 4
Sample Output
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.HINT

题目的意思是让你从1走到5;求最短路径上的点,可以先求一遍Dijkstra,用pre数组记录下它前面的数是几,再从5找它前面的数,找到则ans+1;

代码

#include<cstring>
#include<cstdio>
#include<cmath>
#include<algorithm>
using namespace std;
const int N=1000000001;
int n,m;
int f[1005][1005],dis[1005],pre[1005];
bool is[1005];
int main(){
	while(scanf("%d%d",&n,&m)!=EOF){
		memset(is,false,sizeof(is));      //在新的一轮前清空
		memset(pre,0,sizeof(pre));
		for(int i=1;i<=m;i++)      //预处理
		for(int j=1;j<=m;j++)
			f[i][j]=N;
		for(int i=1,a,b;i<=n;i++){
			scanf("%d%d",&a,&b);
			f[a][b]=1;
		}
		for(int i=1;i<=m;i++)
		dis[i]=N;
		dis[1]=0;
		for(int i=1;i<=m;i++){
			int k=0,minn=N;
			for(int j=1;j<=m;j++)
			if(!is[j]&&minn>dis[j]){
					k=j;
					minn=dis[j];
				}
			if(minn==N)break;
			is[k]=true;
			for(int j=1;j<=m;j++)
			if(!is[j]&&dis[k]+f[k][j]<dis[j]){
				dis[j]=dis[k]+f[k][j];
				pre[j]=k;      //记录前一个点
			}
		}
		if(dis[m]==N)       //不能历遍输出-1
			printf("-1\n");
		else{
			int tot=pre[m],ans=2;//起点+终点=2;
			while(tot!=1){    //while找点
				ans++;
				tot=pre[tot];
			}
			printf("%d\n",ans);
		}
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值