CodeForce题解 —— Disjoint Sets Union 题集:C. Experience

题目相关

题目链接

CodeForce网站。https://codeforces.com/edu/course/2/lesson/7/1/practice/contest/289390/problem/C

题面

In a novel online game, the players fight the monsters and get the experience, as usual. To fight monsters players join together in raid teams. After the destruction of the monster, all the players of the team get the same amount of experience points. The special feature of the game is that a team cannot be split up and no one can leave a team. The only supported operation is to join two teams together.

Since there are already a lot of people playing the game, you are asked to maintain the experience points of the players.

输入

The first line of the input contains two integers n and m (1 \leq n, m \leq 2*10^5) — the number of players and the number of queries.

Next m lines contain the description of queries, one per line. A query can be of three types:

  • join X Y — join two teams to which players X and Y belong to (if they are already in the same team, nothing changes).
  • add X V — add V (1 ≤ V ≤ 100) experience points to each player in a team to which player X belongs to.
  • get X — output the current number of experience points of player X.

Initially, each player has 0 experience points and each of the player is in its own team of size one.

输出

For each query get X output the current number of experience points of player X on a separate line.

样例输入

3 6
add 1 100
join 1 3
add 1 50
get 1
get 2
get 3

样例输出

150
0
50

题解报告

题目分析

本题是一个 DSU(Disjoint Sets Union)的模板题,本题的难度在于如何记录成绩。最简单的思路就是在 DSU 模板中增加一个 vector 用来表示成绩,在每次 add 操作的时候,遍历关系,将所有同一个父节点的数据进行操作。类似代码如下:

    //加分
    void score(T x, T num) {
        _score[x]+=num;
        for (int i=0; i<_n; i++) {
            if (i!=x && relation(x, i)) {
                _score[i]+=num;
            }
        }
    }

这样做,可以达到程序的目的,但是考虑到数据为 2*10^5,每次 add 操作时间复杂度为 O(N),这样的算法在大数据集肯定导致 TLE。因此,我们的问题变成如何将 O(N) 优化。

我们可以参考 DSU 的 find_root() 函数实现。

    //查找x的父亲
    T find_root(T u) {
        return (u== _p[u] ? u : find_root(_p[u]));
    }

使用递归的思路,将分数分为两个部分,也就是两个 vector,一个 vector 保存父节点为自己的分数,一个 vector 保存在 join 操作时候,对应的子节点分数。而 add 操作变更父节点的成绩。这样,我们可以模仿 find_root 通过递归来实现计算所有分数。完整代码如下。

    T score(T u) {
        return u==_p[u] ? _score[u]: (_score[u]-_extra[u]+score(_p[u]));
    }

当然也可以使用一个附加的数据保存节点关系,在 add 的时候,遍历节点关系。但是这个思路没有测试过。

样例数据分析

我们使用样例数据来解释一下这个分数保存过程。

初始状态

序号   _p   _score    _extra
0     0    0         0
1     1    0         0
2     2    0         0
3     3    0         0

如上述数据可知,现在有 3 个集合,分别为:{1}、{2}、{3}。

add 1 100

为 1 号加 100 分。这样我们对应的数据如下。

序号   _p   _score    _extra
0     0    0         0
1     1    100       0
2     2    0         0
3     3    0         0

join 1 3

将数据 1 和 3 合并,这样,我们的集合变成两个,分别为:{1 3} 和 {2}。由于是合并操作,所以我们要记录下对应数据如下:

序号   _p   _score    _extra
0     0    0         0
1     1    100       0
2     2    0         0
3     1    0         100

add 1 50

为 1 号加 100 分。这样我们对应的数据如下。

序号   _p   _score    _extra
0     0    0         0
1     1    150       0
2     2    0         0
3     1    0         100

get 1

由于 1 号是跟节点,因此直接输出 _score[1] 的数据 150。

get 2

由于 1 号是跟节点,因此直接输出 _score[2] 的数据 0。

get 3

由于 3 号是跟节点,需要递归计算。_score[3]-_extra[3]+score(_p[3])=0-100+score(1)=0-100+150=50。

AC代码

//https://codeforces.com/edu/course/2/lesson/7/1/practice/contest/289390/problem/C
//C. Experience

#include <bits/stdc++.h>

using namespace std;

//Disjoint Set Union
template <class T>
struct DSU {
private:
    /*
    当_p[x]<0的时候,说明x的父节点是自己。同时 |_p[x]| 表示集合内元素数量
    当_p[x]>0的时候,表示父节点
    */
    T _n;//数据容量
    std::vector<T> _p;//并查集关系
    std::vector<T> _size;//集合大小
    std::vector<T> _min;//最小值
    std::vector<T> _max;//最大值
    std::vector<T> _score;//分数
    std::vector<T> _extra;//以前分数

public:
    DSU(T n) : _n(n), _p(n, 0), _size(n, 1), _min(n, 0), _max(n, 0), _score(n, 0), _extra(n, 0) {
        iota(_p.begin(), _p.end(), 0);
        iota(_min.begin(), _min.end(), 0);
        iota(_max.begin(), _max.end(), 0);
    }
  
    //查找x的父亲
    T find_root(T u) {
        return (u== _p[u] ? u : find_root(_p[u]));
    }
 
    //建立关系
    bool union_set(T u, T v) {
        if (u<0 || u>=_n || v<0 || v>=_n) {
            return false;
        }
        u = find_root(u);
        v = find_root(v);
        if (u==v) {
            //两个已经在同一个集合
            return false;
        }
        if (_size[u]<_size[v]) {
            //保证不会出现单边增长
            swap(u, v);
        }
        _p[v] = u;
        _size[u] += _size[v];
        _min[u] = std::min(_min[u], _min[v]);
        _max[u] = std::max(_max[u], _max[v]);
        _extra[v] = _score[u];
        return true;
    }
 
    //查找u和v是否在同一个父亲
    bool relation(T u, T v) {
        if (u<0 || u>=_n || v<0 || v>=_n) {
            return false;
        }
        return find_root(u) == find_root(v);
    }

    //数据 u 所在集合大小
    T size(T u) {
        if (u<0 || u>=_n) {
            return 0;
        }
        return _size[find_root(u)];
    }

    //
    T min(T u) {
        if (u<0 || u>=_n) {
            return 0;
        }
        T t=find_root(u);
        return _min[t];
    }

    T mau(T u) {
        if (u<0 || u>=_n) {
            return 0;
        }
        T t=find_root(u);
        return _max[t];
    }

    //加分
    void score(T u, T num) {
        u=find_root(u);
        _score[u]+=num;
    }

    T score(T u) {
        return u==_p[u] ? _score[u]: (_score[u]-_extra[u]+score(_p[u]));
    }
}; //end of struct

int main() {
#if 1
    //提交到 CodeForces 需要使用快读,本地测试的时候,可以不使用。
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
#endif

    int n,m;
    cin>>n>>m;

    DSU<int> dsu(n+1);
    for (int i=0; i<m; i++) {
        string op;
        int u,v;
        cin>>op;
        if ("join"==op) {
            cin>>u>>v;
            dsu.union_set(u, v);
        } else if ("add"==op) {
            cin>>u>>v;
            dsu.score(u, v);
        } else if ("get"==op) {
            cin>>u;
            int ans=dsu.score(u);
            cout<<ans<<"\n";
        }
    }

    return 0;
}

 

### 回答1: #include <stdio.h> int main(){ //定义一个3*3的数组用来存储棋盘 int board[3][3]={0}; int x,y,turn=1; while (1){ //打印棋盘 printf("当前棋盘:\n"); for (x=0;x<3;x++){ for (y=0;y<3;y++){ printf("%d ",board[x][y]); } printf("\n"); } //根据turn的值来判断谁轮到落子 if (turn==1){ printf("轮到X落子,请输入落子的位置(x y):"); }else { printf("轮到O落子,请输入落子的位置(x y):"); } scanf("%d %d",&x,&y); //将落子位置的值设置为对应的值 board[x][y] = turn; //改变轮到谁落子 turn = -turn; //判断谁赢了 if (board[0][0]==board[1][1] && board[1][1]==board[2][2] && board[2][2]!=0){ printf("游戏结束,获胜者是%c\n",board[0][0]==1?'X':'O'); break; } if (board[2][0]==board[1][1] && board[1][1]==board[0][2] && board[0][2]!=0){ printf("游戏结束,获胜者是%c\n",board[2][0]==1?'X':'O'); break; } for (x=0;x<3;x++){ if (board[x][0]==board[x][1] && board[x][1]==board[x][2] && board[x][2]!=0){ printf("游戏结束,获胜者是%c\n", board[x][0] == 1 ? 'X' : 'O'); break; } if (board[0][x]==board[1][x] && board[1][x]==board[2][x] && board[2][x]!=0){ printf("游戏结束,获胜者是%c\n", board[0][x] == 1 ? 'X' : 'O'); break; } } } return 0; } ### 回答2: 为了回答这个问题,需要提供题目的具体要求和规则。由于提供的信息不够具体,无法为您提供准确的代码。但是,我可以给您一个简单的Tic-tac-toe游戏的示例代码,供您参考: ```c #include <stdio.h> #include <stdbool.h> // 判断游戏是否结束 bool isGameOver(char board[][3]) { // 判断每行是否有3个相同的棋子 for(int i = 0; i < 3; i++) { if(board[i][0] != '.' && board[i][0] == board[i][1] && board[i][0] == board[i][2]) { return true; } } // 判断每列是否有3个相同的棋子 for(int i = 0; i < 3; i++) { if(board[0][i] != '.' && board[0][i] == board[1][i] && board[0][i] == board[2][i]) { return true; } } // 判断对角线是否有3个相同的棋子 if(board[0][0] != '.' && board[0][0] == board[1][1] && board[0][0] == board[2][2]) { return true; } if(board[0][2] != '.' && board[0][2] == board[1][1] && board[0][2] == board[2][0]) { return true; } return false; } // 输出棋盘 void printBoard(char board[][3]) { for(int i = 0; i < 3; i++) { for(int j = 0; j < 3; j++) { printf("%c ", board[i][j]); } printf("\n"); } } int main() { char board[3][3]; // 初始化棋盘 for(int i = 0; i < 3; i++) { for(int j = 0; j < 3; j++) { board[i][j] = '.'; } } int player = 1; // 玩家1先下 int row, col; while(true) { printf("Player %d's turn:\n", player); printf("Row: "); scanf("%d", &row); printf("Column: "); scanf("%d", &col); // 判断输入是否合法 if(row < 0 || row >= 3 || col < 0 || col >= 3 || board[row][col] != '.') { printf("Invalid move. Try again.\n"); continue; } // 下棋 board[row][col] = (player == 1) ? 'X' : 'O'; // 输出棋盘 printBoard(board); // 判断游戏是否结束 if(isGameOver(board)) { printf("Player %d wins!\n", player); break; } // 切换玩家 player = (player == 1) ? 2 : 1; } return 0; } ``` 这段代码实现了一个简单的命令行下的Tic-tac-toe游戏。玩家1使用'X'棋子,玩家2使用'O'棋子。玩家依次输入行和列,下棋后更新棋盘,并判断游戏是否结束。当游戏结束时,会输出获胜者并结束游戏。 ### 回答3: 题目要求实现一个井字棋游戏的判断胜负函数。给定一个3x3的井字棋棋盘,用C语言编写一个函数,判断当前是否存在某个玩家获胜或者平局。 题目要求代码中定义一个3x3的字符数组board来表示棋盘,其中 'X' 表示玩家1在该位置放置了一个棋子, 'O' 表示玩家2在该位置放置了一个棋子, '.' 表示该位置没有棋子。 下面是实现此题的C语言代码: ```c #include <stdio.h> #include <stdbool.h> // 用于使用bool类型 bool checkWin(char board[3][3]) { // 检查每一行是否有获胜的情况 for (int row = 0; row < 3; row++) { if (board[row][0] == board[row][1] && board[row][1] == board[row][2] && board[row][0] != '.') { return true; } } // 检查每一列是否有获胜的情况 for (int col = 0; col < 3; col++) { if (board[0][col] == board[1][col] && board[1][col] == board[2][col] && board[0][col] != '.') { return true; } } // 检查对角线是否有获胜的情况 if ((board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[0][0] != '.') || (board[0][2] == board[1][1] && board[1][1] == board[2][0] && board[0][2] != '.')) { return true; } return false; // 没有获胜的情况 } int main() { char board[3][3]; // 存储棋盘状态 // 读取棋盘状态 for (int i = 0; i < 3; i++) { scanf("%s", board[i]); } // 调用检查胜负的函数,并输出结果 if (checkWin(board)) { printf("YES\n"); } else { printf("NO\n"); } return 0; } ``` 这个程序中定义了一个函数checkWin,用于检查是否有玩家获胜。遍历棋盘的每一行、每一列和对角线,判断是否有连续相同的字符且不为'.',如果有,则返回true;否则返回false。 在主函数main中,首先定义一个3x3的字符数组board,然后通过循环从标准输入中读取棋盘状态。接着调用checkWin函数进行胜负判断,并根据结果输出"YES"或者"NO"。最后返回0表示程序正常结束。 请注意,该代码只包含了检查胜负的功能,并没有包含其他如用户输入、判断平局等功能。如果需要完整的游戏代码,请告知具体要求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

努力的老周

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值