跳到正文

题解

题解:CF1470D Strange Housing

_Ch1F4N_约 2 分钟
原文
文章信息与版本

文章信息

发布
2024年10月14日
收录
2025年12月12日
更新
2026年11月17日
篇幅
约 2 分钟
获赞
1
题目
CF1470D

版本

  1. v1当前

不联通一定无解。

否则去 dfs 并染色,这样构造一定有解。

不妨在 dfs 的过程中归纳证明:被 dfs 过的节点一定与 11 联通。

假设当前点颜色为 11,其拓展出去的点不染色,但是一定可以通过当前点与 11 联通。

否则拓展出去的点邻域中假若已经有了被染色的点则可以通过其与 11 联通,否则就会将拓展出去的点染色,则可以通过当前点与 11 联通。

C++
#include<bits/stdc++.h>
using namespace std;
const int maxn = 3e5+114;
int col[maxn],vis[maxn];
vector<int> vec,E[maxn];
int cnt,n,m;
void dfs(int u){
    col[u]=1;
    vis[u]=1;
    cnt++;
    for(int v:E[u]){
        if(vis[v]==1&&col[v]==1) col[u]=0;
    }
    if(col[u]==1) vec.push_back(u);
    for(int v:E[u]){
        if(vis[v]==0) dfs(v);
    }
}
void work(){
    cin>>n>>m;
    cnt=0;
    for(int i=1;i<=n;i++) E[i].clear(),vis[i]=col[i]=0;
    for(int i=1;i<=m;i++){
        int u,v;
        cin>>u>>v;
        E[u].push_back(v);
        E[v].push_back(u);
    }
    dfs(1);
    if(cnt==n){
        cout<<"YES\n";
        cout<<vec.size()<<'\n';
        for(int x:vec) cout<<x<<' ';
        cout<<'\n';
        vec.clear();
    }else{
        cout<<"NO\n";
        vec.clear();
    }
}
signed main(){
    ios::sync_with_stdio(0);
    cin.tie(0),cout.tie(0);
    int T;
    cin>>T;
    while(T--) work();
    return 0;
}
原文