题意:
有 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;
}