Catowice City

Catowice City

题目链接

思路:\(i\) 个人认识第 \(j\) 只猫,所以选了第 \(i\) 个人就必须选第 \(j\) 个人,那么我们连一条 \(i\) 指向 \(j\) 的边。

那么同一个连通分量中就必须同时选择。考虑不能对其他猫产生影响,我们可以选择一个没有出边的强连通分量全部选人(即编号为1的强连通分量),其他选猫即可。注意特判,如果只有一个强连通分量,那么说明不存在合法解。

代码

#include<bits/stdc++.h>
using namespace std;
#define ff first
#define ss second
#define pb push_back
#define all(u) u.begin(), u.end()
#define endl '\n'
#define sz(u) (int)(u.size())
#define debug(x) cout<<#x<<":"<<x<<endl;
typedef pair<int, int> PII;
typedef long long LL;
const int inf = 0x3f3f3f3f;
const int N = 1e6 + 10, M = 105;
const int mod = 1e9 + 7;
const int cases = 1;

int n,m;
vector<int> e[N];
stack<int> stk;
int dfn[N],low[N],tot;
int instk[N],scc[N],siz[N],cnt;
void tarjan(int u){
   dfn[u]=low[u]=++tot;
   stk.push(u);instk[u]=1;
   for(auto v:e[u]){
      if(!dfn[v]){
         tarjan(v);
         low[u]=min(low[u],low[v]);
      }else if(instk[v]) low[u]=min(low[u],dfn[v]);
   }
   if(dfn[u]==low[u]){
      int v;cnt++;
      do{
         v=stk.top();
         stk.pop();
         instk[v]=0;
         scc[v]=cnt;
         siz[cnt]++;
      }while(v!=u);
   }
}

void Showball(){
   cin>>n>>m;
   for(int i=1;i<=n;i++){
    e[i].clear();
    low[i]=0;dfn[i]=0;
    siz[i]=0;scc[i]=0;
    instk[i]=0;
  }
  cnt=0;tot=0;
   while(m--){
      int u,v;
      cin>>u>>v;
      if(u==v) continue;
      e[u].pb(v);
   }  
   for(int i=1;i<=n;i++){
      if(!dfn[i]) tarjan(i);
   }
   if(cnt==1) return cout<<"No\n",void();
   cout<<"Yes\n";
   cout<<siz[1]<<" "<<n-siz[1]<<endl;
   for(int i=1;i<=n;i++) if(scc[i]==1) cout<<i<<" ";
   cout<<endl;
   for(int i=1;i<=n;i++) if(scc[i]!=1) cout<<i<<" ";
   cout<<endl;
}
int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    int T=1;
    if(cases) cin>>T;
    while(T--)
    Showball();
    return 0;
}
posted @ 2024-05-19 20:53  Showball  阅读(3)  评论(0编辑  收藏  举报