zoukankan      html  css  js  c++  java
  • 【luogu P2296 寻找道路】 题解

    题目链接:https://www.luogu.org/problemnew/show/P2296

    题意:给定起点终点,找一条从起点到终点的最短路径使路上的每个点都能有路径到达终点。

    我们先反着建一遍图,然后从终点开始bfs一遍图,标记所有终点可以到达的点。然后再枚举一遍点,如果这个点是终点没法到达的点,那么再枚举这个点所能连接的所有点,如果这些点是终点可以到达的,那么这些点就是不符合条件的。最后在符合条件的点上做一遍最短路。

    #include <queue>
    #include <cstdio>
    #include <cstring>
    #include <iostream>
    #include <algorithm>
    using namespace std;
    const int maxn = 200010;
    int start, end, n, m, u[maxn], v[maxn], dis[maxn];
    bool vis1[maxn], vis2[maxn], vis[maxn];
    struct edge{
    	int from, to, next, len;
    }e1[maxn<<2], e[maxn<<2];
    int cnt1, cnt, head1[maxn], head[maxn];
    void add1(int u, int v, int w)
    {
    	e1[++cnt1].from = u;
    	e1[cnt1].len = w;
    	e1[cnt1].to = v;
    	e1[cnt1].next = head1[u];
    	head1[u] = cnt1;
    }
    void add(int u, int v, int w)
    {
    	e[++cnt].from = u;
    	e[cnt].len = w;
    	e[cnt].to = v;
    	e[cnt].next = head[u];
    	head[u] = cnt;
    }
    queue<int> q1, q;
    void bfs()
    {
    	q1.push(end), vis1[end] = 1;
    	while(!q1.empty())
    	{
    		int now = q1.front();
    		q1.pop();
    		for(int i = head1[now]; i != -1; i = e1[i].next)
    		{
    			if(!vis1[e1[i].to])
    			{
    				vis1[e1[i].to] = 1;
    				q1.push(e1[i].to);
    			}
    		}
    	}
    	memcpy(vis2, vis1, sizeof(vis1));
    	for(int i = 1; i <= n; i++)
    	{
    		if(vis1[i] == 0)
    		for(int j = head1[i]; j != -1; j = e1[j].next)
    		{
    			if(vis2[e1[j].to] == 1)
    				vis2[e1[j].to] = 0;
    		}
    	}
    }
    void SPFA()
    {
    	q.push(start);
    	vis[start] = 1, dis[start] = 0;
    	while(!q.empty())
    	{
    		int now = q.front();
    		q.pop();
    		for(int i = head[now]; i != -1; i = e[i].next)
    		{
    			if(dis[e[i].to] > dis[now] + e[i].len)
    			{
    				dis[e[i].to] = dis[now] + e[i].len;
    				if(!vis[e[i].to])
    				{
    					q.push(e[i].to);
    				}
    			}
    		}
    	}
    }
    int main()
    {
    	memset(head1, -1, sizeof(head1));
    	memset(head, -1, sizeof(head));
    	scanf("%d%d",&n,&m);
    	for(int i = 1; i <= n; i++) dis[i] = 233333333;
    	for(int i = 1; i <= m; i++)
    	{
    		scanf("%d%d",&u[i],&v[i]);
    		if(u[i] != v[i])
    		add1(v[i], u[i], 1);
    	}
    	scanf("%d%d",&start,&end);
    	bfs();
    	for(int i = 1; i <= m; i++)
    	{
    		if(u[i] != v[i] && vis2[u[i]] != 0 && vis2[v[i]] != 0)
    		add(u[i], v[i], 1);
    	}
    	SPFA();
    	if(dis[end] == 233333333)
    	{
    		printf("-1
    ");
    		return 0;
    	}
    	else
    	printf("%d
    ",dis[end]);
    	return 0;
    }
    
  • 相关阅读:
    二叉搜索树与双向链表
    复杂链表的复制
    二叉树中和为某一值的路径
    二叉树的后序遍历
    从上往下打印二叉树
    栈的压入,弹出序列
    包含min函数的栈
    JS基础知识
    有序列表、无序列表、网页的格式和布局
    样式表(宽度和高度、背景字体、对齐方式边界与边框)
  • 原文地址:https://www.cnblogs.com/MisakaAzusa/p/9642087.html
Copyright © 2011-2022 走看看