noip2014 寻找道路

题目:寻找道路

思路:
反着建图,以终点为起点跑一边dfs,标记可以到达的点。
再正着建图,对于每个点,如果它被标记且指向的所有点都被标记那么这个点就可以被经过。
然后保留这些点,跑一边bfs就好。

代码:

#include<bits/stdc++.h>
using namespace std;

#define read(x) scanf("%d",&x)
#define maxn 10000
#define maxm 200000

int n,m;
vector<int> a[maxn+5];
vector<int> g[maxn+5];
int s,t;

bool vis[maxn+5];
bool canuse[maxn+5];

void dfs(int x) {
	vis[x]=true;
	for(int i=0; i<g[x].size(); i++) {
		int y=g[x][i];
		if(vis[y]) continue;
		dfs(y);
	}
}

queue<int> que;
int dist[maxn+5];

int bfs() {
	que.push(s);
	vis[s]=true;
	if(!canuse[s]) return -1;
	while(!que.empty()) {
		int h=que.front();
		que.pop();
		for(int i=0; i<a[h].size(); i++) {
			int y=a[h][i];
			if(y==t) return dist[h]+1;
			if(vis[y]) continue;
			vis[y]=true;
			if(!canuse[y]) continue;
			dist[y]=dist[h]+1;
			que.push(y);
		}
	}
	return -1;
}

int main() {
	read(n),read(m);
	for(int i=1; i<=m; i++) {
		int x,y;
		read(x),read(y);
		a[x].push_back(y);
		g[y].push_back(x);
	}
	read(s),read(t);
	dfs(t);

	for(int i=1; i<=n; i++) {
		if(!vis[i]) continue;
		for(int j=0; j<a[i].size(); j++) {
			if(!vis[a[i][j]]) goto END;
		}
		canuse[i]=true;
END:
		;
	}
	memset(vis,0,sizeof(vis));
	int x=bfs();
	printf("%d",x);

	return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值