CSP算法模板分享
一、出栈 c++
//记忆结构:先进先出:栈;遇到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);
}
小结
新接触算法,只知道其意思,不会运用;后续要多刷题强化!