数据结构相关模版

单链表模版

                                  /* 用数组模拟单链表--静态链表*/
#include<iostream>
using namespace std;
const int N = 10010;
int head, e[N], ne[N], idx;
//head是头结点
//e[i]是节点i的下标
//ne[i]是节点i的next指针是多少
//idx储存当前已经用到了哪个节点

void init()//初始化链表
	{
	head = -1;
	idx = 0;
	}
void add_to_head(int x)//把x插入到头节点
{
	e[idx] = x;
	ne[idx] = head;
	head = idx;
	idx++;
}
void add(int k, int x)//把x插入到下标是k的节点的后面
{
	e[idx] = x;
	ne[idx] = ne[k];
	ne[k] = idx;
	idx++;
}
void remove(int k)//把下标为k的节点后面的点删除
{
	ne[k] = ne[ne[k]];
}
int main()
{
	int m;
	cin >> m;
	init();//初始化
	while (m--)
	{
		char op;
		int k, x;
		cin >> op;
		if (op == 'H')
		{
			cin >> x;
			add_to_head(x);
		}
		else if (op == 'D')
		{
			cin >> k;
			if (!k)head = ne[head];//让head指向头节点的下一个节点
			else
				remove(k - 1);
		}
		else {
			cin >> k >> x;
			add(k - 1, x);//插入的点从0开始
		}
	}
	for (int i = head; i != -1; i = ne[i]) cout << e[i] << " ";
	cout << endl;
}

单调栈


#include<iostream>
using namespace std;
const int N = 10010;
int stk[N], tt;
int main()
{
	int n;
	cin >> n;
	for (int i = 0; i < n; i++)
	{
		int x;
		cin >> x;
		while (tt && stk[tt] >= x) tt--;//弹出当前栈顶元素
		if (tt) cout << stk[tt] << " ";//如果栈顶不为空,即当前栈顶元素就是x左边最近且最小的元素
		else cout << -1 << " ";
		stk[++tt] = x;//把当前x插入到栈里面
	}
	return 0;
}

并查集

并查集算法
#include<iostream>
using namespace std;
const int N = 10010;
int p[N];//存储当前节点的父节点
int find(int x)
{
	if (p[x] != x) p[x] = find(p[x]);//优化:路径压缩
	return p[x];
}
int main()
{
	int n, m;
	scanf("%d%d", &m, &n);
	for (int i = 1; i <= n; i++)  p[i] = i;//初始化,让每个节点指向自己

	while (m--)  
	{
		char op[2];
		int a, b;
		scanf("%s%d%d", op, &a, &b);
		if (*op == 'M')p[find(a)] = find(b);//合并,让a存储的父节点p[a]指向b
		else
		{
			if (find(a) == find(b)) puts("Yes");
			else
				puts("No");
		}
	}
	return 0;
}


模拟散列表(拉链法)


#include<iostream>
#include<cstring>
using namespace std;
const int N = 10003;
int h[N], e[N], ne[N], idx;
//把范围1e9 的数 映射成 1e5 范围
//拉链法
void insert(int x) // 插入操作
{
	int k = (x % N + N) % N; // 令x变为正数
	e[idx] = x;
	ne[idx] = h[k];
	h[k] = idx++;
}
bool find(int x)  //查询操作
{
	int k = (x % N + N) % N;
	for (int i = h[k]; i != -1; i = ne[i])
	{
		if (e[i] == x)  //找到该数
			return true;
	}
	return false;
}
int main()
{
	int n;
	cin >> n;
	memset(h, -1, sizeof h);
	while (n--)  //n次操作
	{
		string op;
		int x;
		cin >> op >> x;
		if (op == "I")  //插入
		{
			insert(x);
		}
		else // 查询操作
		{
			if (find(x)) puts("Yes");
			else
				puts("No");
		}
	}
	return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

YY...yy

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

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

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

打赏作者

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

抵扣说明:

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

余额充值