PAT 天梯赛 L2-007. 家庭房产 【并查集】

本文介绍了一种算法实现,该算法通过并查集的方法来处理家庭成员间的关系,并最终统计每个家庭的人数、房产数量及面积等信息。代码使用C++编写,详细展示了如何进行家庭成员间的合并操作及统计数据的过程。

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

题目链接

https://www.patest.cn/contests/gplt/L2-007

思路
将一个家庭里的所有人都并进去
然后最后查找的时候 找到所有同一个家庭的人,计算出人数,人均房产套数,人均房产面积 而且 在ID 小于当前 ID 的时候 要更新

AC代码

#include <cstdio>
#include <cstring>
#include <ctype.h>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <ctime>
#include <iostream>
#include <algorithm>
#include <deque>
#include <vector>
#include <queue>
#include <string>
#include <map>
#include <stack>
#include <set>
#include <numeric>
#include <sstream>
#include <iomanip>
#include <limits>

using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair <int, int> pii;
typedef pair <ll, ll> pll;

const double PI  = 3.14159265358979323846264338327;
const double E   = 2.718281828459;
const double eps = 1e-6;

const int INF    = 0x3f3f3f3f;
const int maxn   = 1e6 + 5;
const int MOD    = 1e9 + 7;

int pre[10000];

int find(int x)
{
    while (pre[x] != x)
        x = pre[x];                   
    return x; 
}

void join(int x, int y)
{
    int fx = find(x), fy = find(y);
    if (x != fy)
        pre[fx] = fy;
}   

struct Node
{
    int id;
    int total;
    int tot;
    double ave, area;
}temp, q[maxn];

bool comp(Node x, Node y)
{
    if (fabs(x.area - y.area) < eps)
        return x.id < y.id;
    return x.area > y.area;
}

int main()
{
    for (int i = 0; i < 10000; i++)
        pre[i] = i;
    int n;
    cin >> n;
    map <int, Node> m;
    map <int, int> vis; 
    for (int i = 0; i < n; i++)
    {
        int id, a, b, k;
        scanf("%d%d%d%d", &id, &a, &b, &k);
        vis[id] = 1;
        if (a != -1)
        {
            join(id, a);
            vis[a] = 1;
        }   
        if (b != -1)
        {
            join(id, b);
            vis[b] = 1;
        }   
        for (int j = 0; j < k; j++)
        {
            scanf("%d", &a);
            if (a != -1)
            {
                join(id, a);
                vis[a] = 1;
            }
        }
        scanf("%d%d", &a, &b);
        m[id].id   = id;
        m[id].tot  = a;
        m[id].area = b;
    }
    map <int, int>::iterator it, iter;
    int count = 0;
    for (it = vis.begin(); it != vis.end(); it++)
    {
        temp.id   = 0;
        temp.tot  = 0;
        temp.tot  = 0;
        temp.ave  = 0.0;
        temp.area = 0.0;
        if (it -> second == 1)
        {
            it -> second = 0;
            int flag   = find(it -> first);
            temp.id    = it -> first;
            temp.tot  += m[it -> first].tot;
            temp.area += m[it -> first].area;
            temp.total = 1;
            for (iter  = it, iter++; iter != vis.end(); iter++)
            {
                if (iter -> second == 1 && flag == find(iter -> first))
                {
                    iter -> second = 0;
                    if (m[iter -> first].id == iter -> first)
                    {
                        if (iter -> first < temp.id)
                            temp.id = iter -> first;
                        temp.tot  += m[iter -> first].tot;
                        temp.area += m[iter -> first].area;
                    }
                    temp.total ++;
                }
            }
            temp.ave  = temp.tot * 1.0 / temp.total;
            temp.area /= temp.total;
            q[count++] = temp;
        }
    }
    sort (q, q + count, comp);
    printf("%d\n", count);
    for (int i = 0; i < count; i++)
    {
        printf("%04d %d %.3lf %.3lf\n", q[i].id, q[i].total, q[i].ave, q[i].area);
    }
}












### 关于 PAT 天梯赛 L2-001 紧急救援 的分析 题目描述通常涉及在一个加权图中找到从起点到终点的最短路径,同时满足某些条件(如最大权重边最小)。此类问题可以通过 **Dijkstra算法** 和 **优先队列优化** 来解决。 #### 图论基础回顾 在图论中,单源最短路径问题是经典的算法问题之一。对于带正权值的有向无环图 (Directed Acyclic Graph, DAG),或者一般的加权图,Dijkstra 是一种高效的解决方案[^1]。该算法通过维护一个优先队列来动态更新节点的距离,并逐步扩展已知最优路径至目标节点。 针对本题的具体需求——不仅需要求出最短路径长度,还需要记录路径上的最大权重以及可能的不同路径数量,以下是详细的解答思路: --- #### 数据结构设计 为了高效处理输入数据并支持后续查询操作,需定义如下辅助类或变量: 1. 使用邻接表存储图的信息。 2. 定义三个数组分别保存当前顶点的状态: - `dist[v]` 表示从起始点到达 v 的最短距离; - `max_edge[v]` 记录从起点到 v 路径上遇到的最大边权值; - `path_count[v]` 统计有多少条不同的路径能够达到相同的 `(dist[v], max_edge[v])` 值组合。 初始化时设所有顶点不可达 (`inf`) 并设置起点状态为零。 --- #### 主要逻辑流程 采用 Dijkstra 算法的核心思想,结合优先队列实现多维度比较功能。具体步骤如下所示: 1. 初始化优先队列 PQ,按照三元组 `(distance, maximum edge weight, node)` 排序,其中 distance 应作为主要关键字升序排列,maximum edge weight 则次之降序排列。 2. 将初始结点加入队列,其对应的距离和最大边权均置为 0;路径数记作 1。 3. 循环提取队首元素 u 进行松弛操作:遍历与 u 相连的所有邻居 w,尝试更新它们的相关属性。如果发现更优解,则同步调整 dist[w], max_edge[w] 及 path_count[w] 的取值;当新旧两方案具有相同效果时累加路径数目即可。 4. 结束循环直至访问完全图中的每一个可触及位置为止。 最终输出结果应包括总耗时、途中经历过的最高危险等级数值以及符合条件的有效路线总数模去某个固定常量后的余数形式呈现出来。 --- #### 实现代码样例 下面是基于 Python 编写的完整程序版本: ```python import heapq def dijkstra(n, start, end, graph): INF = float('inf') # Initialize arrays to store distances, max edges and counts. dist = [INF]*n max_edge = [-1]*n count = [0]*n pq = [(0, 0, start)] # Priority queue with tuple of (current_distance, current_max_edge, vertex). dist[start] = 0 max_edge[start] = 0 count[start] = 1 while pq: d_u, m_e_u, u = heapq.heappop(pq) if u == end: break for v, cost in graph[u]: alt_dist = d_u + cost # Compute the new potential 'max edge' value along this route. candidate_me_v = max(m_e_u, cost) if alt_dist < dist[v]: dist[v] = alt_dist max_edge[v] = candidate_me_v count[v] = count[u] # Push updated state into priority queue. heapq.heappush(pq, (alt_dist, candidate_me_v, v)) elif alt_dist == dist[v] and candidate_me_v < max_edge[v]: max_edge[v] = candidate_me_v count[v] += count[u] return dist[end], max_edge[end], count[end]%int(1e9+7) if __name__ == "__main__": n_vertices, n_edges, src, dst = map(int, input().split()) g = [[]for _ in range(n_vertices)] for i in range(n_edges): a,b,cost=map(int,input().strip().split()) g[a].append((b,cost)) res=dijkstra(n_vertices,src,dst,g) print(*res) ``` 上述脚本实现了完整的读入解析过程并通过标准输入获取必要的参数配置信息之后调用了核心函数完成任务执行最后按指定格式打印答案内容. --- #### 时间复杂度分析 由于采用了二叉堆作为底层支撑的数据结构,在每次迭代过程中最多只需要 O(log E) 的时间成本来进行插入/删除动作,因此整体运行效率大致维持在线性对数级别范围内即 O(E log V)。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值