PAT 天梯赛 L2-010. 排座位 【并查集】

本文介绍了一种使用并查集处理朋友关系及直接敌对关系的方法,并通过一个具体的编程实例展示了如何利用该方法解决特定问题。文章讨论了如何区分朋友与敌对关系的不同处理方式,并给出了详细的AC代码实现。

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

题目链接

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

思路

因为 题意中 朋友的朋友 就是朋友 那么 朋友的关系 用 并查集 保存
但是 敌对关系 只有直接的敌对关系才是具有敌对关系 所以直接用结构体保存就好

AC代码

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

using namespace std;
typedef long long LL;

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

const int MAXN = 0x3f3f3f3f;
const int MINN = 0xc0c0c0c0;
const int maxn = 1e2 + 5;
const int MOD  = 1e9 + 7;

int pre[maxn];

struct Node
{
    vector <int> v;
};

map <int, Node> M;

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

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

bool Hos(int x, int y)
{
    vector <int>::iterator it;
    for (it = M[x].v.begin(); it != M[x].v.end(); it++)
    {
        if ((*it) == y)
            return true;
    }
    return false;
}

int main()
{
    int n, m, k;
    scanf("%d%d%d", &n, &m, &k);
    for (int i = 0; i < 2; i++)
    {
        for (int j = 0; j <= n; j++)
            pre[j] = j;
    }
    int x, y, flag;
    for (int i = 0; i < m; i++)
    {
        scanf("%d%d%d", &x, &y, &flag);
        if (flag == 1)
            join(x, y);
        else
        {
            M[x].v.push_back(y);
            M[y].v.push_back(x);
        }   
    }
    for (int i = 0; i < k; i++)
    {
        scanf("%d%d", &x, &y);
        if (find(x) == find(y))
        {
            if (Hos(x, y) == true)
                printf("OK but...\n");
            else
                printf("No problem\n");
        }
        else
        {
            if (Hos(x, y) == true)
                printf("No way\n");
            else
                printf("OK\n");
        }
    }
}
### 关于 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、付费专栏及课程。

余额充值