1.前缀和用来求解一段区间内的数字和
例子:
原 数 列:1 2 3 4 5 6 7 8 9
前缀和数列:1 3 6 10 15 21 28 36 45
用a来表示原数列 用s来表示前缀和数列
s[i] = a[1] + a[2] + a[3] + ... +a[i];
优点:时间快速
for (int i=1;i<=n;i++)
{
cin >> a[i];
s[i] = s[i-1] + a[i];
}
s[L] 和s[R]分别表示位:
s[L]=a[1]+a[2]+...+a[L];
s[R]=a[1]+a[2]+...+a[L]+a[L+1]+a[L+2]+...+a[R];(L<=R)
要求区间[L,R]内的和
也就是: a[L]+a[L+1]+...+a[R];
区间[L,R]的和为:
s[R]-s[L-1]=a[L]+a[L+1]+...+a[R];
#include <iostream>
using namespace std;
{
int n,m;
cin >> n >> m;
for(int i=1;i<=n;i++)
cin >> a[i];
for(int i=1;i<=n;i++)
s[i]=s[i-1]+a[i];
while (m--)
{
int l,r;
cin >> l >> r;
cout << s[r]-s[l-1];
}
return 0;
}
2.
sort函数头文件为<algorithm>
sort(first,last)对容器内或普通数组中(first,last)范围内的元素进行进行排序,默认进行升序排列。
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int t[10]={3,4,2,1,8,7,5,6,9,0}
sort(&t[0],&t[10]);
for(int i=0;i<10;i++)
cout<<t[i]<<" ";
return 0;
}
输出:i
0 1 2 3 4 5 6 7 8 9
如果从大到小,那就反向输出,需要用到cmp这个参数
bool cmp(int a,int b)
return a>b;
}
int main()
{
int t[10]={3,4,2,1,8,7,5,6,9,0}
sort(t,t+10,cmp);
for(int i=0;i<=10;i++)
cout<<t[i]<<" ";
return 0;
}
输出
9 8 7 6 5 4 3 2 1 0
3.
swap函数交换两个容器内所有元素
void swap(int *a,int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
};
int main()
{
int a,b;
cin>>a>>b;
swap(a,b);
cout<<a<<b;
}