C语言、C++ CSP算法模板分享

CSP算法模板分享

一、出栈 c++

例子:洛谷 P1427 小鱼的数字游戏

//记忆结构:先进先出:栈;遇到0停止输出 
#include <iostream>
#include <stack> 
using namespace std;
int main()
{
	stack<int> s;
	int a;
	while(true){
		cin >> a;
		if(a==0) break;  //遇到0停止输出
		s.push(a);
	}
	
	while(s.size()>0){
		cout << s.top()<<" ";
		s.pop();
	}
}

二、C语言–树状数组

1.单点修改、前缀和查询

//树状数组 :求前n项和、改变某位置的数值 [单点修改、前缀和查询]
#include <stdio.h>
//#define lowbit(x) ((x)&(-x)) //宏定义 
//求lowbit 取一个二进制最低位的一与后边的0组成的数
int lowbit(int x) {
	return x&(-x);
}
//修改某位置元素的数值 
void add(int p,int x) {
	while(p < N) {
		a[p] += x;
		p += lowbit(p);
	}
}
//计算前n项和 Long long int -->ll 
ll count(int p) {  
	ll result = 0;
	while(p) {
		result += b[p];
		p -= lowbit(p);
	}
	return result;
}

int main () {
	
	return 0;
}

2.单点查询、前缀和查询

//树状数组模板:单点查询、查询前缀和[动态维护区间操作]
#include <stdio.h>

void add (int x, int k)
{
	for(; x <= n;x += x & =x) t[x] += k;
}

int ask(int x){
	int ans = 0;
	for(; x;x -= x & -x) ans += t[x];
	return ans;
}


int main()
{
	
	retrun 0;
 } 

3.栈–c语言

//栈--c语言 
#include<stdio.h>
#include<malloc.h>
#include<string.h>

//定义栈
typedef struct{
	int data[100];
	int top;
	int bottom;
}stack;

//创建栈
stack *StackCreate(){
	stack *p=(stack*)malloc(sizeof(stack));//分配新空间
	if(p==NULL)//分配失败
	return 0;
	p->bottom=p->top=0;//分配成功
	return p;
}

//入栈
void StackInput(stack *p,char str){
	p->data[p->top]=str;//存入栈中
	p->top++;//栈顶指针加1
}

//出栈
char StackOutput(stack *p,char str){
	if(p->top!=p->bottom){//栈非空
		str=p->data[p->top-1];//栈顶内容输出
		p->top--;//栈顶减1
		return str;
	}
}

//输出
void StackPrint(stack *p){
	while(p->top!=p->bottom){
		printf("%c",p->data[p->top-1]);
		p->top--;
	}
}

//主函数
int main(){
	int i;
	stack *p;//定义栈名
	char a[10]="asdfgh";
	p=StackCreate();//创建栈
	for(i=0;i<strlen(a);i++)//将字符串a的字符入栈
	StackInput(p,a[i]);
	printf("输出栈中所有字符:\n");
	StackPrint(p);
}

小结

新接触算法,只知道其意思,不会运用;后续要多刷题强化!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值