hdu4582 DFS spanning tree

该博客讨论了如何在无向图中找到DFS生成树,并解决如何选择最少的边来确保每个环至少包含一条边。问题转化为在树上染色,确保所有给定链上至少有一条黑边。通过贪心策略,按照链的父节点深度排序并尽可能向高层染色,可以找到最优解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

给定一个无向图,求出它的DFS生成树。

非树边与树边会构成环,现在选择树上的最少的边数,使得每一个环都至少有一条边被选中。


一个环对应的就是树上的一条路径,因为DFS树的性质这条路径只可能是从一个节点出发连向它的儿子。

所以问题就转化成了给定树上的一些简单链,给树上的边染黑白两色,使得每条给定的链上都至少有一条黑边,求最小黑边数量。


假如树是一条长链,则每一个链对应的就是一段区间,就成了经典的贪心问题,只需以右端点为关键字排序然后对于每一个未满足要求的区间尽量往右染即可。

在一般的树上也可以这样贪心,只需按链的父节点的深度为关键字进行排序,尽可能往“高”染色,


#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <cstdlib>
#include <cmath>
#include <cctype>
#include <queue>
#include <stack>
#include <utility>
#include <set>
#define pb push_back
#define mp make_pair
#define fi first
#define se second
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
#define N 2005
int n , m , pre[N] , mcnt , f[N] , dep[N];
struct edge
{
  int x , f , next;
}e[40005];
pair<int , int> a[20005];
bool vis[N];
void dfs(int x , int fa)
{
  f[x] = fa , dep[x] = dep[fa] + 1 , vis[x] = 1;
  for (int i = pre[x] ; ~i ;i = e[i].next)
    if (!vis[e[i].x])
      e[i].f = e[i ^ 1].f = 1 , dfs(e[i].x , x);
}

bool cmp(pair<int , int> x, pair<int , int> y)
{
  if (dep[x.se] == dep[y.se])
    return dep[x.fi] > dep[y.fi];
  return dep[x.se] > dep[y.se];
}

void work()
{
  int i , j , x , y , ans = 0;

  memset(pre , -1 , sizeof(pre));
  mcnt = 0;
  for (i = 1 ; i <= m ; ++ i)
  {
    scanf("%d%d",&x,&y);
    a[i] = make_pair(x , y);
  }
  for (i = m ; i > 0 ; -- i)
  {
    x = a[i].fi , y = a[i].se;
    e[mcnt] = (edge) {y , 0 , pre[x]} , pre[x] = mcnt ++;
    e[mcnt] = (edge) {x , 0 , pre[y]} , pre[y] = mcnt ++;
  }
  memset(vis , 0 , sizeof(vis));
  dfs(1 , 0);
  m = 0;
  for (x = 1 ; x <= n ; ++ x)
    for (i = pre[x] ; ~i ; i = e[i].next)
      if ((i & 1) && !e[i].f)
      {
        y = e[i].x;
        a[++ m] = make_pair(x , y);
        if (dep[a[m].fi] < dep[a[m].se])
          swap(a[m].fi , a[m].se);
      }
  sort(a + 1 , a + m + 1 , cmp);
  memset(vis , 0 , sizeof(vis));
  for (i = 1 ; i <= m ; ++ i)
  {
    x = a[i].fi , y = a[i].se;
    //cout << x <<' '<< y << endl;
    while (f[x] != y)
      if (vis[x])
        break;
      else x = f[x];
    if (!vis[x])
      vis[x] = 1 , ++ ans;
  }
  printf("%d\n" , ans);
}

int main()
{
  while (scanf("%d%d",&n,&m) , n || m)
    work();
  return 0;
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值