AtCoder Beginner Contest 216 D - Pair of Balls (思维建图 拓扑排序判断有向图是否有环)

原题链接

题意:

n n n个数,每个数都会出现两次。 m m m个柱子,并给出柱子上的数。当且仅当两个相同的数都处于柱子的最上面时,才能够将两个数删除。问最后能否将柱子的数都删除。

思路:

思维建图,对于一个柱子上的数 1 , 2 1,2 1,2,从 1 1 1 2 2 2连单向边,表明只有 1 1 1拿走了 2 2 2才能拿走。
最后得到有向图,如果有环的话,就是 N o No No。比如 1 − > 2 − > 3 − > 1 1->2->3->1 1>2>3>1说明只有 1 1 1拿了 2 2 2才能拿, 2 2 2拿了 3 3 3才能拿, 3 3 3拿了 1 1 1才能拿,会陷入死循环。
用拓扑排序判断是否有环就好了。

代码:

// Problem: D - Pair of Balls
// Contest: AtCoder - AtCoder Beginner Contest 216
// URL: https://atcoder.jp/contests/abc216/tasks/abc216_d
// Memory Limit: 1024 MB
// Time Limit: 2000 ms
// 
// Powered by CP Editor (https://cpeditor.org)

#include<iostream>
#include<cstdio>
#include<string>
#include<ctime>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<stack>
#include<climits>
#include<queue>
#include<map>
#include<set>
#include<sstream>
#include<cassert>
#include<bitset>
#include<list>
#include<unordered_map>
//#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<ll, ll>PLL;
typedef pair<int, int>PII;
typedef pair<double, double>PDD;
#define I_int ll
inline ll read(){ll x = 0, f = 1;char ch = getchar();while(ch < '0' || ch > '9'){if(ch == '-')f = -1;ch = getchar();}while(ch >= '0' && ch <= '9'){x = x * 10 + ch - '0';ch = getchar();}return x * f;}

inline void write(ll x){if (x < 0) x = ~x + 1, putchar('-');if (x > 9) write(x / 10);putchar(x % 10 + '0');}

#define read read()
#define closeSync ios::sync_with_stdio(0);cin.tie(0);cout.tie(0)
#define multiCase int T;cin>>T;for(int t=1;t<=T;t++)
#define rep(i,a,b) for(int i=(a);i<=(b);i++)
#define repp(i,a,b) for(int i=(a);i<(b);i++)
#define per(i,a,b) for(int i=(a);i>=(b);i--)
#define perr(i,a,b) for(int i=(a);i>(b);i--)

ll ksm(ll a, ll b,ll mod){ll res = 1;while(b){if(b&1)res=res*a%mod;a=a*a%mod;b>>=1;}return res;}

const int maxn=2e5+100;

vector<int>g[maxn];
int din[maxn];

int main() {
	int n=read,m=read;
	rep(i,1,m){
		int k=read,las=read;
		rep(j,1,k-1){
			int x=read;
			g[las].push_back(x);
			din[x]++;
			las=x;
		}
	}
	queue<int>q;
	rep(i,1,n){
		if(!din[i]) q.push(i);
	}
	int cnt=0;
	while(!q.empty()){
		int u=q.front();q.pop();
		cnt++;
		for(auto t:g[u]){
			if(--din[t]==0) q.push(t);
		}
	}
	if(cnt==n) puts("Yes");
	else puts("No");
	
	
	
	
	
	
	
	return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

豆沙睡不醒

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值