lower_bound()
函数介绍
lower_bound()返回一个 iterator 它指向在[first,last)标记的有序序列中可以插入value,而不会破坏容器顺序的第一个位置,而这个位置标记了一个大于等于value 的值。 例如,有如下序列: ia[]={12,15,17,19,20,22,23,26,29,35,40,51}; 用值21调用lower_bound(),返回一个指向22的iterator。用值22调用lower_bound(),也返回一个指向22的iterator。第一个版本使用底层的 < (小于)操作符,第二个版本根据comp进行排序和比较。注意事项
调用lower_bound之前必须确定序列为有序序列,否则调用出错。第一个版本排序根据底层的 <(小于)操作符,第二个版本根据comp进行排序。
智商问题 链接网址:http://tyvj.cn/Problem_Show.asp?id=1463
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
int a[1000000], n;
int main() {
std::ios::sync_with_stdio(false);
cin >> n;
for (int i = 0; i < n; ++i)
cin >> a[i];
sort(a, a + n);
int t;
while (cin >> t)// 返回t在a数组中排第几个位置
cout << lower_bound(a, a + n, t) - a + 1 << endl;
return 0;
}
因为题中数据量过大所以要用到std::ios::sync_with_stdio(false);作用是可以来消除iostream的输入输出缓存,可以节省很多时间.
有了那个语句之后,iostream 的效率和 stdin 就相差无几了。
集合
链接网址:http://poj.org/problem?id=1053
#include<iostream>
#include<string>
#include<set>
#include<algorithm>
using namespace std;
char ss[13][5];
int main()
{
int i,j,k,num;
set<char>tmp[4];
while(scanf("%s",ss[0])!=EOF)
{
for(i=1;i<12;i++)
scanf("%s",ss[i]);
printf("CARDS: ");
for(i=0;i<12;i++)
printf(" %s",ss[i]);
printf("\n");
num=0;
for(i=0;i<12;i++)
for(j=i+1;j<12;j++)
for(k=j+1;k<12;k++)
{
tmp[0].insert(ss[i][0]); //将3个字符串的第1列元素插入到编号为0的set容器中
tmp[0].insert(ss[j][0]);
tmp[0].insert(ss[k][0]);
tmp[1].insert(ss[i][1]);
tmp[1].insert(ss[j][1]);
tmp[1].insert(ss[k][1]);
tmp[2].insert(ss[i][2]);
tmp[2].insert(ss[j][2]);
tmp[2].insert(ss[k][2]);
tmp[3].insert(ss[i][3]);
tmp[3].insert(ss[j][3]);
tmp[3].insert(ss[k][3]);
if((tmp[0].size()==1||tmp[0].size()==3)
&&(tmp[1].size()==1||tmp[1].size()==3)
&&(tmp[2].size()==1||tmp[2].size()==3)
&&(tmp[3].size()==1||tmp[3].size()==3))
{
num++;
if(num==1)
printf("SETS: 1. %s %s %s\n",ss[i],ss[j],ss[k]);
else
printf(" %d. %s %s %s\n",num,ss[i],ss[j],ss[k]);
}
tmp[0].clear();
tmp[1].clear();
tmp[2].clear();
tmp[3].clear();
}
if(num==0)
printf("SETS: *** None Found ***\n");
printf("\n");
}
//system("pause");
return 0;
}
图
链接网址:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=109
#include<iostream>
#include<string>
#include<cstdio>
#include<map>
using namespace std;
int main()
{
char s[100],s1[100],s2[100];
string str;
map <string,string> my;
map <string,string>::iterator t;
while(cin.getline(s,100))
{
str=s;
if(str=="") break;
sscanf(s,"%s%s",s1,s2);
my[s2]=s1;
}
while(cin>>s)
{
if(my.find(s)!=my.end()) cout<<my[s]<<endl;
else cout<<"eh"<<endl;
}
// system("pause");
return 0;
}