[BZOJ1674]&&[Usaco2005]Part Acquisition

描述 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.

输入格式 InputFormat

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.

输出格式 OutputFormat

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

样例输入 SampleInput

9 7
6 2
1 6
7 2
4 1
2 5
1 4
2 4
7 7
3 3

样例输出 SampleOutput

-1

来源 Source

Silver


BZOJ 1674


代码 Code

spfa. 原题还需要输出顺序呢。

#include <stdio.h>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
using namespace std;
const int inf=0x7fffffff/11.27;
int i,j,t,n,m,l,r,k,z,y,x;
inline void read(int &x)
{
    x=0;char ch=getchar();
    while (ch<'0' || ch>'9') ch=getchar();
    while (ch>='0' && ch<='9') x=x*10+ch-'0',ch=getchar();
}
struct edge
{
    int to,next,val;
}e[100005];
int head[10005],dis[10005],f[10005];
bool used[10005];
deque <int> q;
int cnt=0;
inline void ins(int u,int v,int w)
{
    e[++cnt].to=v;e[cnt].next=head[u];e[cnt].val=w;
    head[u]=cnt;
}
inline void spfa(int s)
{
    int i,j,t,u,v,w;
    while (!q.empty()) q.pop_front();
    for (i=1;i<=n;i++) dis[i]=inf;
    memset(used,false,sizeof(used));
    dis[s]=0;q.push_back(s);used[s]=true;
    while (!q.empty())
    {
        u=q.front();q.pop_front();used[u]=false;
        for (i=head[u];i;i=e[i].next)
        {
            v=e[i].to;w=e[i].val;
            if (dis[v]>dis[u]+w)
            {
                dis[v]=dis[u]+w;
                if (!used[v])
                {
                    used[v]=true;
                    if (!q.empty() && dis[q.front()]>=dis[v]) q.push_front(v);
                    else q.push_back(v);
                }
            }
        }
    }
}
int main()
{
    read(n);read(k);
    for (i=1;i<=n;i++)
    {
        read(x);read(y);
        ins(x,y,1);
    }
    spfa(1);
    if (dis[k]==inf)
    {
        printf("-1\n");
        return 0;
    }
    printf("%d\n",dis[k]+1);
    return 0;
}