Part Acquisition
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 2842 Accepted: 1231 Special Judge
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).
* Lines 2..T+1: The ordered list of the objects that the cows possess in the sequence of trades.
Sample Input
6 5
1 3
3 2
2 3
3 1
2 5
5 4
Sample Output
4
1
3
2
5
Hint
OUTPUT DETAILS:
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
交换商品。求交换次数最多的。并输出结点
代码:
#include<cstdio>
#include<cmath>
#include<string>
#include<cstring>
#include<queue>
#include<algorithm>
#include<iostream>
#include<cstring>
using namespace std;
#define INF 1000000001
int n,m;
int a,b;
bool vis[1001];
int pre[1001];
int dis[1001];
int ans[1001];
int map[1001][1001];
void dijkstra(){
memset(vis,false,sizeof(vis));
for(int i=1;i<=n;i++){
dis[i]=INF;
}
dis[1]=0;
int k;
for(int i=1;i<=n;i++){
int min=INF;
for(int j=1;j<=n;j++){
if(!vis[j]&&dis[j]<min){
k=j;
min=dis[j];
}
}
if(min==INF) break;
vis[k]=true;
for(int j=1;j<=n;j++){
if(!vis[j]&&dis[j]>dis[k]+map[k][j]){
dis[j]=map[k][j]+dis[k];
pre[j]=k;
}
}
}
}
void init(){
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
map[i][j]=INF;
for(int i=1;i<=m;i++){
scanf("%d%d",&a,&b);
map[a][b]=1;
}
}
int main(){
while(scanf("%d%d",&m,&n)!=EOF){
memset(pre,0,sizeof(pre));
int sum=0;
init();
dijkstra();
if(dis[n]==INF) printf("-1\n");
else{
ans[sum++]=n;
int temp=pre[n];//记录前驱结点的个数
while(temp!=1){
ans[sum++]=temp;
temp=pre[temp];
}
ans[sum++]=1;
printf("%d\n",sum);
for(int i=sum-1;i>=0;i--)
printf("%d\n",ans[i]);
}
}
return 0;
}