vector属于动态数组,可以动态的观测和使用数组。与静态数组相比在某些题的求解中有着非常大的优势。以下由几个比较经典的约瑟夫问题展示。
1 n个人中数到第m个人删除,后面不断重复数到m个删除,算出最后一个人的编号。
#include<bits/stdc++.h>
using namespace std;
vector<int>a;
int n,m;
int main(){
while(cin>>n>>m){
a.clear();
for(int i=0;i<n;i++)a.push_back(i);//初始化
int pos=0;
for(int i=0;i<n-1;i++){
pos=(pos+m-1)%a.size();
a.erase(a.begin()+pos);
}
printf("%d",a[0]+1);
}
}
2 圆桌问题
hdu 4841
#include<bits/stdc++.h>
using namespace std;
vectora;
int n,m;
int main(){
while(cin>>n>>m){
a.clear();
for(int i=0;i<2n;i++)a.push_back(i);//初始化
int pos=0;
for(int i=0;i<n;i++){
pos=(pos+m-1)%a.size();
a.erase(a.begin()+pos);
}
int j=0;
for(int i=0;i<2n;i++){
if(i&&!(i%50))cout<<endl;
if(j<a.size()&&a[j]==i){
cout<<“G”;
j++;
}
else cout<<“B”;
}
cout<<endl<<endl;
}
}
vector一部分常规操作
vectorname;
vectora;
赋值 a.push_back();
元素个数 a.size();
判断是否为空 a.empty()
打印 cout<<a[i]<<endl
清空 a.clear()
删除 a.erase(a.beagin()+pos) 删除第pos+1个对应的值
排序 sort(a.begin(),a.end())
map
map有点像之前python里学过的字典,一个键对应一个值。
操作是 map<类型,类型>name
map<string,int>student
student[string(name)]=int(id);
相比定义两个数组查找(复杂度位O(n))而此库复杂度为O(log(2,n));
sort
sort函数是常用的排序函数。
使用方式
sort(begin,end)//默认是从小到大排序
sort(begin,end,cmp)
定义sort排序方式
#include<bits/stdc++.h>
using namespace std;
struct Student{
int score;
};
bool cmp(Student a,Student b)
{
return a.score>b.score;
}
int main()
{ Student a[5];
for(int i=0;i<5;i++)
cin>>a[i].score;
sort(a,a+5,cmp);
for(int i=0;i<5;i++)
cout<<a[i].score<<endl;
}