(Nowcoder) 牛客寒假算法基础集训营4 F Applese 的QQ群 (二分+拓扑)

5 篇文章 0 订阅
3 篇文章 0 订阅

视频题解戳我

传送门

题目描述

Applese 有一个QQ群。在这个群中,大家互相请教问题。如 b 向 a 请教过问题,就把 a 叫做是 b 的"老板"。这样一个群中就会有很多老板。
同时规定:如果 a 是 b 的老板,b 是 c 的老板,那么 a 也是 c 的老板。
为了不破坏群里面和谐交流的氛围,Applese 定了一个群规:不允许出现 a 既是 b 的老板, b 又是 a 的老板。
你需要帮助 Applese 判断大家是否遵守了群规。

输入描述:

第一行两个整数 n, m,表示群里的人数以及请教问题的数量。
接下来 m 行,每行两个整数 a, b,表示 a 是 b 的"老板",即 b 向 a 请教了一个问题。
注:无论是否违反了群规,a 都会成为 b 的老板。

输出描述:

对于每次提问,输出一行"Yes"表示大家都遵守了群规,反之输出"No"。

示例1

输入

4 4
1 2
2 3
3 1
1 4

输出

Yes
Yes
No
No

备注:

1≤n≤1051≤n≤105
1≤m≤2⋅1051≤m≤2⋅105
1≤a,b≤n

解题思路:这题其实就是让我们判断给的图中是否有环,有环就是No,无环就是Yes,从题目来看肯定是一段Yes,一段No,从某个人开始是No,那接下来肯定都是有环的了,都是No,所以这题我们可以二分那个分割点(分割Yes和No),然后用拓扑去判断是否有环,当然也可以用tarjan判断,视频就是用的这种。

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<string>
#include<cstring>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<cmath>
#include<sstream>
using namespace std;
typedef long long ll;
const ll inf=0x3f3f3f3f;
const int maxn=2e5+5;
int in[maxn],n,m;
vector<int> e[maxn]; 
int fr[maxn],to[maxn];
bool check(int mid){
	for(int i=1;i<=n;++i){
		in[i]=0;
		e[i].clear();
	}
	for(int i=1;i<=mid;++i){
		e[fr[i]].push_back(to[i]);
		in[to[i]]++;
	}
	queue<int> q;
	for(int i=1;i<=n;++i){
		if(!in[i])	q.push(i);
	}
	while(!q.empty()){
		int np=q.front();
		q.pop();
		for(int i=0;i<(int)e[np].size();++i){
			int nto=e[np][i];
			in[nto]--;
			if(!in[nto])	q.push(nto);
		}
	}
	for(int i=1;i<=n;++i)	if(in[i])	return false;
	return true;
}
int main(){
	std::ios::sync_with_stdio(0);
	cin>>n>>m;
	for(int i=1;i<=m;++i){
		cin>>fr[i]>>to[i];
	}
	int le=1,ri=m,mid,ans=0;
	while(le<=ri){
		mid=(le+ri)>>1;
		if(check(mid)){
			le=mid+1;
			ans=mid;
		}
		else	ri=mid-1;
	}
	for(int i=1;i<=ans;++i)	cout<<"Yes"<<endl;
	for(int i=ans+1;i<=m;++i)	cout<<"No"<<endl;
	return 0;
}




 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值