NOIP2014 Day2 T2(BFS+最短路)

输入的时候构造一个原图一个反图,然后先从终点倒搜一次标记可以访问的点,然后再从终点跑一次最短路即可,几乎没有难度,放上以前写的代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<queue>
#include<vector>
#define ms(i,j) memset(i,j, sizeof i);
using namespace std;
int n,m;
vector<int> edge[10005];
vector<int> zedge[10005];
bool vi[10005];//是否访问过
int ind[10005];//是否与终点连通
int s,t;
int ans = -1;
void bfs1()//处理与终点连通
{
queue<int> q;
ms(ind,0);
q.push(t); ind[t] = 1;
while (!q.empty())
{
int u = q.front(); q.pop();
for (int i=0;i<edge[u].size();i++)
{
int v = edge[u][i];
if (!ind[v])
{
ind[v]=1;
q.push(v);
}
}
}
}
struct node {int u,s;};
void bfs2()
{
queue<node> q;
ms(vi,false);
q.push((node){t,0}); vi[t] = true;
while (!q.empty())
{
node u = q.front(); q.pop();
if (u.u==s)
{
ans = u.s; return ;
}
for (int i=0;i<edge[u.u].size();i++)
{
int v = edge[u.u][i];
bool flag = false;
for (int k=0;k<zedge[v].size();k++)
if (ind[zedge[v][k]]==0) {flag = true; break;}
if (flag) continue;
if (!vi[v])
{
vi[v] = true;
q.push((node){v,u.s+1});
}
}
}
}
int main()
{
scanf("%d%d", &n,&m);
for (int i=1;i<=m;i++)
{
int x,y;
scanf("%d%d", &x, &y);
if (x==y) continue;
edge[y].push_back(x);//反向边
zedge[x].push_back(y);//正向边
}
scanf("%d%d", &s, &t);
bfs1();
bfs2();
printf("%d\n", ans);
return 0;
}
------ 本文结束 ------