洛谷P2325 [SCOI2005]王室联邦——题解

本文介绍了一种使用深度优先搜索(DFS)算法解决特定问题的方法,该问题要求将地图上的城市合理地划分为若干个省份。通过从每个城市出发进行DFS,并利用栈来追踪访问过程,当访问的城市数量达到一定阈值时,便将其划分为一个省份,以此来实现地图的划分。

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

题目传送门
题目大意:
题面说得很清楚了。


思考过程:
其实这个题很奇怪,既没要求最多可能分多少个省,又没要求城市数最多的省的城市数最小是多少,所以有很多种做法。


具体做法:
从1开始做dfs,对所有点维护一个栈,第一次到这个点则让他入栈,回溯时如果比第一次到时栈中元素多了n个或以上,则将这一部分弹栈,划分成一个省,省会为当前回溯的城市,最后未划分的城市和最后被划分一个省合为一个省就行了,这样就能保证划分的正确性。


代码:

#include <bits/stdc++.h>
using namespace std;

const int maxn=1100;
struct stu
{
    int to,next;    
}road[maxn*2]; int first[maxn],cnt=0;
int be[maxn],root[maxn],fa[maxn],stack1[2*maxn];
int n,b,top;

void addedge(int x,int y)
{
    road[++cnt].to=y;
    road[cnt].next=first[x];
    first[x]=cnt;   
}

void dfs(int now)
{
    int nowtop=top;
    for(int i=first[now];i;i=road[i].next)
    {
        int to=road[i].to;
        if(to==fa[now]) continue;
        fa[to]=now;
        dfs(to);
        if(top-nowtop>=b)
        {
            cnt++;
            root[cnt]=now;
            while(nowtop!=top)
            {
                be[stack1[top]]=cnt;
                top--;
            }
        }
    }
    stack1[++top]=now;
}

int main()
{
    scanf("%d%d",&n,&b);
    for(int i=1;i<=n-1;i++)
    {
        int x,y;
        scanf("%d%d",&x,&y);
        addedge(x,y);addedge(y,x);  
    }
    cnt=0;
    dfs(1);
    while(top>=1)
    {
        be[stack1[top]]=cnt;
        top--;  
    }
    printf("%d\n",cnt);
    for(int i=1;i<=n;i++) printf("%d ",be[i]); printf("\n");
    for(int i=1;i<=cnt;i++) printf("%d ",root[i]); printf("\n");
    return 0;   
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值