题目链接: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\n");
return 0;
}
else
printf("%d\n",dis[end]);
return 0;
}

最新文章

  1. CentOS 6.4 服务器版安装教程(超级详细图解)
  2. insert into linksvr or insert into from linksvr
  3. 这10道javascript笔试题你都会么
  4. MongoDB使用汇总贴
  5. webpack常用的插件安装命令
  6. C语言-08-预处理器
  7. 修改Chrome默认搜索引擎为Google.com
  8. C++ 顺序表
  9. 剑指OFFER之字符串的排列(九度OJ1369)
  10. stap-prep 需要安装那些内核符号
  11. JS与OC交互--简单使用
  12. Linux桌面快捷方式建立方案
  13. Unity3D动态读取外部MP3文件给AudioSource
  14. (转)Spring boot——logback.xml 配置详解(二)
  15. 迈向angularjs2系列(1):typescript指南
  16. python学习之路网络编程篇(第五篇)-续篇
  17. Bootstrap3 栅格系统-栅格参数
  18. 信用评分卡(A卡/B卡/C卡)的模型简介及开发流程|干货
  19. dede织梦后台-退出空白,注销空白,打开空白,登录返回首页,登录返回登录页面
  20. PHP实现螺旋矩阵(螺旋数组)

热门文章

  1. redis(1)简介
  2. Binder or AIDL的最简单实践
  3. C Primer Plus note7
  4. 你必须知道的get与post的真正区别
  5. safari兼容时间格式
  6. dotnet watch+vs code提升asp.net core开发效率
  7. recommendation baselines
  8. leetcode-surrounded regions-ZZ
  9. SQL-SERVER学习(二) 数据表的存储过程
  10. linux和aix内核参数检查