COJ-1092-Barricade

来源:互联网 发布:网络电视机如何使用 编辑:程序博客网 时间:2024/06/05 17:29

1092: Barricade

Submit Page Summary Time Limit: 1 Sec Memory Limit: 32 Mb Submitted: 309 Solved: 102
Description
GBQC国一共有N个城市,标号分别为1, 2, …, N。N个城市间一共有M条单向通行的道路。

不幸的是,GBQC国的城市1连续暴雨,使得整个城市淹没在汪洋洪水中,于是GBQC国领导人小明决定让城市1的居民暂时移居到城市N,于是一场浩浩荡荡的搬迁运动开始了。

但还有一个问题需要解决,居民从城市1出发,如果走到某个城市时面对多条道路,那么城市1的居民就不知道该往哪个方向走了。

为了解决上述问题,GBQC国领导人决定在一些道路的入口处设置“禁止通行”的路障,以确保城市1的居民从城市1出发,途径每个城市时,都有且仅有一条路可供选择,这样城市1的居民就能顺利搬迁到城市N了。

现在GBQC国领导人想知道最少需要设置几个路障呢?

Input
输入包含多组测试数据。

对于每组测试数据,第一行包含两个整数N(2<=N<=10^4), M(0<=M<=10^5),其中N、M的含义同上。接下来一共有M行,每行有三个整数x(1<=x<=N)、y(1<=y<=N),表示GBQC国有一条由城市x进入通向城市y的单向道路。

Output
对于每组测试数据,用一行输出一个整数表示最少需要设置几个路障。如果没办法从城市1出发走到城市N,则输出“-1”(不包括引号)。

Sample Input
3 4
1 1
1 2
1 3
1 3

3 2
1 3
3 2

2 0
Sample Output
3
0
-1
Hint
由于数据量较大,推荐使用scanf和printf。

Source
CSU Monthly 2012 Aug.

题目大意:从1到n,放置一些路障保证不用再岔路口做选择走到n。
解题思路:边权改为出度-1,跑Dijkstra

#include<iostream>#include<climits>#include<cstring>#include<vector>#include<queue>using namespace std;const int MAXN=1e4+10;const int MAXM=1e5+10;const int INF=0x3f3f3f3f;int head[MAXN],nxt[MAXM];int odeg[MAXN],dist[MAXN];bool vis[MAXN];int n,m,en;struct edge{    int v,cost;    bool operator <(const edge &r) const    {        return cost>r.cost;    }}E[MAXM];void init(){    memset(head,0,sizeof(head));    en=0;    memset(odeg,0,sizeof(odeg));    for(int i=1;i<=n;i++) dist[i]=INF;}void addedge(int u,int v){    E[++en].v=v;    nxt[en]=head[u];    head[u]=en;    odeg[u]++;}void dijkstra(int start){    memset(vis,false,sizeof(vis[0])*(n+5));    priority_queue<edge> q;    while(!q.empty()) q.pop();    edge now,tmp;    now.v=start;    now.cost=0;    q.push(now);    while(!q.empty())    {        now=q.top();        q.pop();        if(vis[now.v]) continue;        vis[now.v]=true;        dist[now.v]=now.cost;        for(int i=head[now.v];i;i=nxt[i])        {            int to=E[i].v;            if(!vis[to]&&dist[to]>dist[now.v]+odeg[now.v]-1)            {                dist[to]=dist[now.v]+odeg[now.v]-1;                tmp.cost=dist[to];                tmp.v=to;                q.push(tmp);            }        }    }    if(dist[n]==INF) cout<<"-1"<<endl;    else cout<<dist[n]<<endl;}int main(){    ios::sync_with_stdio(false);    int u,v;    while(cin>>n>>m)    {        init();        for(int i=1;i<=m;i++)        {            cin>>u>>v;            addedge(u,v);        }        dijkstra(1);    }    return 0;}
0 0