0x41 数据结构进阶并查集

A题 程序自动分析

题目链接:https://ac.nowcoder.com/acm/contest/1031/A

题目描述

在实现程序自动分析的过程中,常常需要判定一些约束条件是否能被同时满足。
考虑一个约束满足问题的简化版本:假设 1, 2, 3, ⋯ 代表程序中出现的变量,给定 个形如 = 或 ≠ 的变量相等/不等的约束条件,请判定是否可以分别为每一个变量赋予恰当的值,使得上述所有约束条件同时被满足。例如,一个问题中的约束条件为: 1 = 2, 2 = 3, 3 = 4, 1 ≠ 4 ,这些约束条件显然是不可能同时被满足的,因此这个问题应判定为不可被满足。
现在给出一些约束满足问题,请分别对它们进行判定。

输入描述:

第1行包含1个正整数t,表示需要判定的问题个数。注意这些问题之间是相互独立的。

对于每个问题,包含若干行:
第1行包含1个正整数n,表示该问题中需要被满足的约束条件个数。
接下来n行,每行包括3个整数i,j,e,描述1个相等/不等的约束条件,相邻整数之间用单个空格隔开。若e=1,则该约束条件为xi=xj;若e=0,则该约束条件为xi≠xj。

输出描述:

包括t行。

第k行输出一个字符串“YES”或者“NO”(不包含引号,字母全部大写),“YES”表示输入中的第k个问题判定为可以被满足,“NO”表示不可被满足。

示例1

输入

2
2
1 2 1
1 2 0
2
1 2 1
2 1 1

输出

NO
YES

说明

在第一个问题中,约束条件为:x1=x2,x1≠x2。这两个约束条件互相矛盾,因此不可被同时满足。

在第二个问题中,约束条件为:x1=x2,x2=x1。这两个约束条件是等价的,可以被同时满足。

备注:

1≤n≤100000

1≤i,j≤1000000000

分析:简单并查集,但需进行离散化加速,另外就是初始化要 乘2(WA 4发)

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
inline ll read() { ll s = 0, w = 1; char ch = getchar(); for (; !isdigit(ch); ch = getchar()) if (ch == '-') w = -1; for (; isdigit(ch); ch = getchar())    s = (s << 1) + (s << 3) + (ch ^ 48); return s * w; }
const int maxn = 1e5 + 7;
int t, n;
int f[maxn << 1], a[maxn << 1];
int x[maxn], y[maxn], op[maxn];
int find(int x) { return f[x] == x ? x : f[x] = find(f[x]); }
int main() {
    //freopen("in.txt", "r", stdin);
    //ios::sync_with_stdio(false), cin.tie(0);
    t= read(); while (t--) {
        n = read();
        for (int i = 1; i < maxn << 1; ++i)f[i] = i;
        for (int i = 1; i <= n; ++i) {
            x[i] = read(), y[i] = read(), op[i] = read();
            a[i * 2 - 1] = x[i], a[i * 2] = y[i];
        }
        int m = n << 1;
        sort(a + 1, a + 1 + m);
        m = unique(a + 1, a + 1 + m) - a - 1;
        for (int i = 1; i <= n; ++i) {
            int dx = lower_bound(a + 1, a + 1 + m, x[i]) - a;
            int dy = lower_bound(a + 1, a + 1 + m, y[i]) - a;
            if (op[i])    f[find(dx)] = find(dy);
        }
        int flag = 0;
        for (int i = 1; i <= n; ++i) {
            int dx = lower_bound(a + 1, a + 1 + m, x[i]) - a;
            int dy = lower_bound(a + 1, a + 1 + m, y[i]) - a;
            if (!op[i] and f[find(dx)] == f[find(dy)]) {
                flag = 1;    break;
            }
        }
        if (flag) puts("NO");
        else puts("YES");
    }
    return 0;
}

B题 银河英雄传说

https://ac.nowcoder.com/acm/contest/1031/B

链接:https://ac.nowcoder.com/acm/contest/1031/B
来源:牛客网

题目描述

​ 公元五八○一年,地球居民迁移至金牛座α第二行星,在那里发表银河联邦创立宣言,同年改元为宇宙历元年,并开始向银河系深处拓展。

​ 宇宙历七九九年,银河系的两大军事集*在巴米利恩星域爆发战争。泰山压顶集**宇宙舰队司令莱因哈特率领十万余艘战舰出征,气吞山河集*点名将杨威利组织麾下三万艘战舰迎敌。

​ 杨威利擅长排兵布阵,巧妙运用各种战术屡次以少胜多,难免恣生骄气。在这次决战中,他将巴米利恩星域战场划分成30000列,每列依次编号为1, 2, …, 30000。之后,他把自己的战舰也依次编号为1, 2, …, 30000,让第i号战舰处于第i列(i = 1, 2, …, 30000),形成“一字长蛇阵”,诱敌深入。这是初始阵形。当进犯之敌到达时,杨威利会多次发布合并指令,将大部分战舰集中在某几列上,实施密集攻击。合并指令为M i j,含义为让第i号战舰所在的整个战舰队列,作为一个整体(头在前尾在后)接至第j号战舰所在的战舰队列的尾部。显然战舰队列是由处于同一列的一个或多个战舰组成的。合并指令的执行结果会使队列增大。

​ 然而,老谋深算的莱因哈特早已在战略上取得了主动。在交战中,他可以通过庞大的情报网络随时监听杨威利的舰队调动指令。

​ 在杨威利发布指令调动舰队的同时,莱因哈特为了及时了解当前杨威利的战舰分布情况,也会发出一些询问指令:C i j。该指令意思是,询问电脑,杨威利的第i号战舰与第j号战舰当前是否在同一列中,如果在同一列中,那么它们之间布置有多少战舰。

​ 作为一个资深的高级程序设计员,你被要求编写程序分析杨威利的指令,以及回答莱因哈特的询问。

​ 最终的决战已经展开,银河的历史又翻过了一页……

输入描述:

第一行有一个整数T(1≤T≤500,000),表示总共有T条指令。

以下有T行,每行有一条指令。指令有两种格式:

M i j :i和j是两个整数(1≤i , j≤30000),表示指令涉及的战舰编号。该指令是莱因哈特窃听到的杨威利发布的舰队调动指令,并且保证第i号战舰与第j号战舰不在同一列。C i j :i和j是两个整数(1≤i , j≤30000),表示指令涉及的战舰编号。该指令是莱因哈特发布的询问指令。

输出描述:

你的程序应当依次对输入的每一条指令进行分析和处理:

如果是杨威利发布的舰队调动指令,则表示舰队排列发生了变化,你的程序要注意到这一点,但是不要输出任何信息;

如果是莱因哈特发布的询问指令,你的程序要输出一行,仅包含一个整数,表示在同一列上,第i号战舰与第j号战舰之间布置的战舰数目。如果第i号战舰与第j号战舰当前不在同一列上,则输出-1。

示例1

输入

4
M 2 3
C 1 2
M 2 4
C 4 2

输出

-1
1

说明

战舰位置图:表格中阿拉伯数字表示战舰编号

#include<bits/stdc++.h>
using namespace std;
const int maxn = 5e5 + 10;
int f[maxn], d[maxn], cnt[maxn];//并查集,结点x到根节点s[x]的路径长度、结点所在集合大小

void init() {
	for (int i = 0; i < maxn; ++i)
		d[i] = 0, cnt[i] = 1, f[i] = i;
}
int find(int x) {
	if (f[x] != x) {
		int root = find(f[x]);
		d[x] += d[f[x]];
		f[x] = root;
	}
	return f[x];
}
// 将结点x合并到结点y所在的集合,更新结点x未合并前所在集合的根节点到合并后的根节点的长度和记录集合数量的值
void merge(int x, int y) {
	x = find(x), y = find(y);
	if (x != y) {
		d[x] = cnt[y];// 更新未合并前x所在集合的根节点到合并后集合的根节点的路径的长度,也就是未合并前y所在集合的元素的数量
		cnt[y] += cnt[x];// 更新合并后的集合的元素的数量.
		f[x] = y;// 更新根节点
	}
}
int main() {
	//freopen("in.txt", "r", stdin);
	ios::sync_with_stdio(false); cin.tie(0);
	init(); int t ,x, y; char c;
	cin >> t;
	while (t--) {
		cin >> c >> x >> y;
		if (c == 'M')
			merge(x, y);
		else if (c == 'C') {
			if (find(x) != find(y))
				cout << "-1" << endl;
			else
				cout << (abs(d[x] - d[y]) - 1) << endl;
		}
	}
	return 0;
}

C题 Parity game

链接:https://ac.nowcoder.com/acm/contest/1031/C

题目描述

Now and then you play the following game with your friend. Your friend writes down a sequence consisting of zeroes and ones. You choose a continuous subsequence (for example the subsequence from the third to the fifth digit inclusively) and ask him, whether this subsequence contains even or odd number of ones. Your friend answers your question and you can ask him about another subsequence and so on. Your task is to guess the entire sequence of numbers.
You suspect some of your friend's answers may not be correct and you want to convict him of falsehood. Thus you have decided to write a program to help you in this matter. The program will receive a series of your questions together with the answers you have received from your friend. The aim of this program is to find the first answer which is provably wrong, i.e. that there exists a sequence satisfying answers to all the previous questions, but no such sequence satisfies this answer.

输入描述:

The first line of input contains one number, which is the length of the sequence of zeroes and ones. This length is less or equal to 1000000000. In the second line, there is one positive integer which is the number of questions asked and answers to them. The number of questions and answers is less or equal to 5000. The remaining lines specify questions and answers. Each line contains one question and the answer to this question: two integers (the position of the first and last digit in the chosen subsequence) and one word which is either `even' or `odd' (the answer, i.e. the parity of the number of ones in the chosen subsequence, where `even' means an even number of ones and `odd' means an odd number).

输出描述:

There is only one line in output containing one integer X. Number X says that there exists a sequence of zeroes and ones satisfying first X parity conditions, but there exists none satisfying X+1 conditions. If there exists a sequence of zeroes and ones satisfying all the given conditions, then number X should be the number of all the questions asked.

示例1

输入

10
5
1 2 even
3 4 odd
5 6 even
1 6 even
7 10 odd

输出

3
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 10;
int n, m;
struct Node {
    int l, r, ans;
}node[maxn];
int a[maxn << 1];
int fa[maxn];

int find(int x) {
    return x == fa[x] ? x : fa[x] = find(fa[x]);
}

void merge(int u, int v) {
    int fau = find(u), fav = find(v);
    fa[fau] = fav;
}


int main() {
    ios::sync_with_stdio(false);
    scanf("%d%d", &n, &m);
    int l, r;
    char op[10];
    int cnt = 1;
    for (int i = 1; i <= m; i++) {
        scanf("%d%d%s", &node[i].l, &node[i].r, op);
        if (op[0] == 'e') node[i].ans = 0;
        else node[i].ans = 1;
        a[cnt++] = node[i].l - 1, a[cnt++] = node[i].r;
    }
    sort(a + 1, a + cnt);
    int sz = unique(a + 1, a + cnt) - a - 1;
    for (int i = 1; i <= m; i++) {
        node[i].l = lower_bound(a + 1, a + 1 + sz, node[i].l - 1) - (a);
        node[i].r = lower_bound(a + 1, a + 1 + sz, node[i].r - 1) - (a);
        //cout<<node[i].l<<" "<<node[i].r<<endl;
    }
    for (int i = 1; i <= 2 * sz + 20; i++) fa[i] = i;
    for (int i = 1; i <= m; i++) {
        int x_odd = node[i].l, x_even = node[i].l + sz + 5;
        int y_odd = node[i].r, y_even = node[i].r + sz + 5;
        if (node[i].ans == 0) {
            if (find(x_odd) == find(y_even) || find(x_even) == find(y_odd)) {
                printf("%d\n", i - 1);
                return 0;
            }
            merge(x_odd, y_odd);
            merge(x_even, y_even);
        }
        else {
            if (find(x_odd) == find(y_odd) || find(x_even) == find(y_even)) {
                printf("%d\n", i - 1);
                return 0;
            }
            merge(x_odd, y_even);
            merge(x_even, y_odd);
        }

    }
    //没有矛盾的情况
    printf("%d\n", m);
    return 0;
}

D题 食物链

链接:https://ac.nowcoder.com/acm/contest/1031/D

题目描述

动物王国中有三类动物A,B,C,这三类动物的食物链构成了有趣的环形。A吃B,B吃C,C吃A。

现有N个动物,以1-N编号。每个动物都是A,B,C中的一种,但是我们并不知道它到底是哪一种。

有人用两种说法对这N个动物所构成的食物链关系进行描述:

第一种说法是“1 X Y”,表示X和Y是同类。

第二种说法是“2 X Y”,表示X吃Y。

此人对N个动物,用上述两种说法,一句接一句地说出K句话,这K句话有的是真的,有的是假的。当一句话满足下列三条之一时,这句话就是假话,否则就是真话。

1) 当前的话与前面的某些真的话冲突,就是假话;

2) 当前的话中X或Y比N大,就是假话;

3) 当前的话表示X吃X,就是假话。

你的任务是根据给定的N(1≤N≤50,000)和K句话(0≤K≤100,000),输出假话的总数。

输入描述:

第一行是两个整数N和K,以一个空格分隔。
以下K行每行是三个正整数 D,X,Y,两数之间用一个空格隔开,其中D表示说法的种类。
若D=1,则表示X和Y是同类。
若D=2,则表示X吃Y。

输出描述:

只有一个整数,表示假话的数目。

示例1

输入

100 7
1 101 1   
2 1 2     
2 2 3     
2 3 3     
1 1 3     
2 3 1     
1 5 5

输出

3

说明

#include<cstdio>
const int maxn = 50000 + 10;
 
int p[maxn]; //存父节点
int r[maxn];//存与父节点的关系 0 同一类,1被父节点吃,2吃父节点
 
void set(int n) //初始化
{
    for (int x = 1; x <= n; x++)
    {
        p[x] = x; //开始自己是自己的父亲节点
        r[x] = 0;//开始自己就是自己的父亲,每一个点均独立
    }
}
 
int find(int x) //找父亲节点
{
    if (x == p[x]) return x;
 
    int t = p[x];
    p[x] = find(p[x]);
    r[x] = (r[x] + r[t]) % 3; //回溯由子节点与父节点的关系和父节点与根节点的关系找子节点与根节点的关系
    return p[x];
}
 
void Union(int x, int y, int d)
{
    int fx = find(x);
    int fy = find(y);
 
    p[fy] = fx; //合并树 注意:被 x 吃,所以以 x 的根为父
    r[fy] = (r[x] - r[y] + 3 + (d - 1)) % 3; //对应更新与父节点的关系
}
 
int main()
{
    int n, m;
    scanf("%d%d", &n, &m);
    set(n);
 
    int ans = 0;
    int d, x, y;
    while (m--)
    {
        scanf("%d%d%d", &d, &x, &y);
 
        if (x > n || y > n || (d == 2 && x == y)) ans++; //如果节点编号大于最大编号,或者自己吃自己,说谎
 
        else if (find(x) == find(y)) //如果原来有关系,也就是在同一棵树中,那么直接判断是否说谎
        {
            if (d == 1 && r[x] != r[y]) ans++; //如果 x 和 y 不属于同一类
            if (d == 2 && (r[x] + 1) % 3 != r[y]) ans++; // 如果 x 没有吃 y (注意要对应Uinon(x, y)的情况,否则一路WA到死啊!!!)
        }
        else Union(x, y, d); //如果开始没有关系,则建立关系
    }
    printf("%d\n", ans);
    return 0;
}
原文地址:https://www.cnblogs.com/RioTian/p/13414922.html