Codeforces Round #649 (Div. 2)D题[dfs求环+深度分层求图中独立集]

D. Ehab’s Last Corollary


题目大意:就是给你一个联通图,你有两种选择
1.你可以输出包含 ⌈ k 2 ⌉ \lceil{k\over2}\rceil 2k个顶点得独立点集,什么是独立点集:集合中任意两点都没有边相连
2.你要找到顶点数 < = k <=k <=k的环


解题思路:求环很简单就是dfs一遍如果深度大的点指向了深度小的点那么就是有环,现在是怎么求独立集?
我们一个想法就是将有边相连的点就将它们分开那么我们就可以按深度进形分层,如果两个点有边按照dfs序肯定不在同一层


#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#define mid ((l + r) >> 1) 
#define Lson rt << 1, l , mid
#define Rson rt << 1|1, mid + 1, r
#define ms(a,al) memset(a,al,sizeof(a))
#define log2(a) log(a)/log(2)
#define _for(i,a,b) for( int i = (a); i < (b); ++i)
#define _rep(i,a,b) for( int i = (a); i <= (b); ++i)
#define for_(i,a,b) for( int i = (a); i >= (b); -- i)
#define rep_(i,a,b) for( int i = (a); i > (b); -- i)
#define lowbit(x) ((-x) & x)
#define IOS std::ios::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define INF 0x3f3f3f3f
#define hash Hash
#define next Next
#define count Count
#define pb push_back
#define f first
#define s second
using namespace std;
const int N = 4e5+10, mod = 1e9 + 7;
const double eps = 1e-10;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> PII;
template<typename T> void read(T &x)
{
    x = 0;char ch = getchar();ll f = 1;
    while(!isdigit(ch)){if(ch == '-')f*=-1;ch=getchar();}
    while(isdigit(ch)){x = x*10+ch-48;ch=getchar();}x*=f;
}
template<typename T, typename... Args> void read(T &first, Args& ... args) 
{
    read(first);
    read(args...);
}
vector<int> G[N], ans, d[N];
int n, m, k;
int dep[N], path[N];

void find(int u, int v)
{
    while(u != v)
    {
        ans.pb(u);
        u = path[u];
    }
    ans.pb(u);
    
    cout << 2 << "\n";
    cout << ans.size() << "\n";
    for(auto it : ans)
      cout << it << " ";
      
    exit(0);
    return;
}

void dfs(int deep, int u)
{
    dep[u] = deep;
    d[deep].pb(u);
    for(auto it : G[u])
    {
        if(dep[it] == -1) 
        {
            path[it] = u;
            dfs(deep+1,it);
        }
        else if(it != path[u] && dep[u] - dep[it] + 1 <= k && dep[u] > dep[it]) 
            find(u,it);
    }
    return;
}

int main()
{
    ms(dep,-1);
    read(n,m,k);
    while(m --)
    {
        int l, r;
        read(l,r);
        G[l].pb(r); G[r].pb(l);
    }
    dfs(0,1);
    int need = (k+1)/2;
    for(int i = 0; i <= n && need; i += 2)
        for(auto it : d[i])
        {
            ans.pb(it);
            if(--need == 0) break;
        }
   
    if(need)
    {
        need = (k+1)/2;
        ans.clear();
    for(int i = 1; i <= n && need; i += 2)
        for(auto it : d[i])
        {
            ans.pb(it);
            if(--need == 0) break;
        }
    }
    cout << "1\n";
    for(auto i : ans)
     cout << i << " ";
     return 0;
}
 

你可能感兴趣的:(图)