Disjoint Set & Segment Tree

1.并查集

并查集模板1

组成集合,问哪个集合人最少。

由于不只是要分集合,还要计算集合人数,所以单独开一个数组存储人数,每个集合的根(或者说组长即set[i]=i 的那个人)也要存储自己集合的人数。

	#include <bits/stdc++.h>
using namespace std;
 
int T;
int N,M;
int a[1005];
int num[1005];
int find(int x){
	
	if( a[x]==x ){
		return x;
	}
	else{
		return find(a[x]);
	}
}
 
int main(){
	scanf("%d", &T);
	while( T--){
		scanf("%d %d", &N, &M);
		
		for(int i=1; i<=N; i++){
			a[i] = i;
			num[i] = 1;
		}
   		for(int i=0; i<M; i++){
			int tmp1, tmp2;
			scanf("%d %d", &tmp1, &tmp2);
			int root1 = find(tmp1);
			int root2 = find(tmp2);
			
			//  不是一个集合
			if( root1 !=root2 ){
				// 人少的集合合并到人多的集合
				if( num[root1] < num[root2] ){
					// 1集合人数少于2集合
					a[root1] = root2;
					num[root2] += num[root1];
				}
				else{
					a[root2] = root1;
					num[root1] += num[root2];
				}
			}
		}
			
			
		int min = 2000;
		for(int i=1; i<=N; i++){
			int root = find(i);
			if( num[root] < min ){
				min = num[root];
			}
		}
		printf("%d\n", min);
	}
}

并查集解图论——让顶点相连

1.最小生成树:并查集可以用来判断两个顶点是不是已经相连,避免出现环(见贪心那章)

2.欧拉通路:让两个顶点相连

10129
Play on Words
Some of the secret doors contain a very interesting word puzzle. The team of archaeologists has to solve
it to open that doors. Because there is no other way to open the doors, the puzzle is very important
for us.
There is a large number of magnetic plates on every door. Every plate has one word written on
it. The plates must be arranged into a sequence in such a way that every word begins with the same
letter as the previous word ends. For example, the word ‘ acm ’ can be followed by the word ‘ motorola ’.
Your task is to write a computer program that will read the list of words and determine whether it
is possible to arrange all of the plates in a sequence (according to the given rule) and consequently to
open the door.
Input
The input consists of T test cases. The number of them ( T ) is given on the first line of the input file.
Each test case begins with a line containing a single integer number N that indicates the number of
plates ( 1 N 100000 ). Then exactly N lines follow, each containing a single word. Each word
contains at least two and at most 1000 lowercase characters, that means only letters ‘ a ’ through ‘ z ’ will
appear in the word. The same word may appear several times in the list.
Output
Your program has to determine whether it is possible to arrange all the plates in a sequence such that
the first letter of each word is equal to the last letter of the previous word. All the plates from the
list must be used, each exactly once. The words mentioned several times must be used that number of
times.
If there exists such an ordering of plates, your program should print the sentence ‘ Ordering is
possible. ’. Otherwise, output the sentence ‘ The door cannot be opened.
Sample Input
3
2
acm
ibm
3
acm
malform
mouse
2
ok
ok
Sample Output
The door cannot be opened.
Ordering is possible.
The door cannot be opened.

【思路】题目要求n个字母,能够首尾相连形成一长串 

将字母看作顶点,字母之间具有有向边,即是否能形成一个欧拉通路(至少是通路可以是回路)

这个题解提供了一个用并查集查找欧拉通路的方法。(因为顶点是有限的)

// Algorithm: Considering letters as nodes and words as directed edges, 
// there is a solution if and only if there is Euler path in the graph. 
// First determine whether it is a connected graph
#include<cstdio>
#include<cstring>
#include<vector>
using namespace std;

const int maxn = 1000 + 5; // the max length of words

// Union-find set
int pa[256]; // 用26个小写字母的ascii码作为并查集初始化的值
int findset(int x) { return pa[x] != x ? pa[x] = findset(pa[x]) : x; } 

int used[256], deg[256]; // used or not; degree

int main() {
  int T;
  scanf("%d", &T);
  while(T--) {
    int n;
    char word[maxn];

    scanf("%d", &n);
    memset(used, 0, sizeof(used));
    memset(deg, 0, sizeof(deg));
    for(int ch = 'a'; ch <= 'z'; ch++) pa[ch] = ch; // Initialize the union-find set
    int cc = 26; // Number of connected graphs 最开始每个字母一组

    for(int i = 0; i < n; i++) {
      scanf("%s", word);
	  // 本道题的关键在于看出 需要一个欧拉通路
	  // 即一个顶点出度==1 一个顶点入度==1 其余顶点出度等于入度
	  // 即一个degree[]==1 一个degree[]==-1 其余degree[]==0
      char c1 = word[0], c2 = word[strlen(word)-1]; // 只用获取首尾
      deg[c1]++;
      deg[c2]--;
      used[c1] = used[c2] = 1;
	  // 首尾必是连通的 同属于一个集合
      int s1 = findset(c1);
	  int s2 = findset(c2);
      if(s1 != s2) { 
		  pa[s1] = s2; 
		  cc--; }  // union 有两个集合合并了 总集合个数-1
    }

    vector<int> d; // 存储起点或终点 若d为空说明构成欧拉回路
    for(int ch = 'a'; ch <= 'z'; ch++) {
      if(!used[ch]) cc--; // Letters not used 去掉没有出现过的字母
      else if(deg[ch] != 0) d.push_back(deg[ch]); // 起点或终点
    }
    bool ok = false;
	// 最后所有出现过的字母构成一个集合 且 构成欧拉回路(所有顶点入=出)或欧拉通路
    if(cc == 1 && (d.empty() || (d.size() == 2 && (d[0] == 1 || d[0] == -1)))) ok = true;
    if(ok) printf("Ordering is possible.\n");
    else printf("The door cannot be opened.\n");
  }
  return 0;
}

2.线段树

为什么有线段树?便于查询数组最大值、最小值、和。

当数组中的值发生修改时,同样需要修改线段树——采用递归,用小区间更新大区间。

线段树是完全二叉树,它的最后一层表示的是单个节点,最上层表示的是0到n的区间。

每个节点存放的是区间和,即最顶层就是数组和,最下层是每个元素的值。

 纯线段树问题

 

#include <bits/stdc++.h>
using namespace std;
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
const int MAXN=50005;
int segTree[MAXN<<2];

// 如果进行了累加 需要自底向上更新sum
void push_up(int x){
	// x节点的值 = 左子节点 + 右子节点
	segTree[x]=segTree[x*2]+segTree[x*2+1];
}

// 递归建立线段树
void build( int l, int r, int root){
	
	if (l==r){ // 找到单节点
		scanf("%d",&segTree[root]);
		return;
	}
            // 没找到单节点
	int mid=(l+r)>>1;
	
	// 递归左右子树
	build( l, mid, root*2);
	build( mid+1, r, root*2+1);
	
	//每次更新父节点值.
	//这里为什么可以更新父节点,其实这里是递归的一个本质
	//递归是基于栈完成的,所以当前操作完成后会返回到上一层,并且执行这个更新的操作,也就更新了父节点
	push_up(root);
}

// 单节点更新 递归
void update(int l, int r, int root, int p, int num){
	// p为节点下标 num为增加或删除的人数
	if (l==r && l==p){ // 找到单节点 更新
		segTree[root] += num;
		return;
	}
	else{// 没找到单节点
        // 二分找p节点
	    int mid=(l+r)>>1;
	    if ( p<=mid ){
		    update(l, mid, root*2, p, num);
	    }else{
		update(mid+1, r, root*2+1, p, num);
	    }
	
	    push_up(root);
    }
	
}

int query(int l,int r,int root, int a, int b){
	
	if ( a<=l && r<=b ){ //在区间内,直接返回
		return segTree[root];
	}
	                // 没在区间内
	int ans=0;
	int mid=(l+r)>>1;
	if ( a<=mid ){
		ans+=query( l, mid, root*2, a, b);
	}
	if ( b>mid ){
		ans+=query(mid+1, r, root*2+1, a, b);
	}
	return ans;
}

int T, N;

int main()
{
	
	char str[10];
	int a,b;
	scanf("%d",&T);
	int i=0;
	while(T--) {
		i ++;
		printf("Case %d:\n",i);
		
		scanf("%d", &N);
		build(1, N, 1); // 建树自上而下 该数组第一层区间是[1, N]
		
		while (true){
			scanf("%s",str);
			if (str[0]=='E') 
				break;
			scanf("%d %d",&b, &a);
			if (str[0]=='A'){
				update(1, N, 1, a, b);
			}
			else if (str[0]=='S'){
				update(1, N, 1, a, -b);
			}
			else if (str[0]=='Q'){
				printf("%d\n", query( 1, N, 1, b, a));
			}
		} 
	}
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值