题面
链接:https://ac.nowcoder.com/acm/contest/7830/A〰 来源:牛客网
题目描述 Jack is worried about being single for his whole life, so he begins to use a famous dating app. In this app, the user is shown single men/women’s photos one by one, and the user may choose between “yes” and “no”. Choosing “yes” means an invitation while choosing “no” means nothing. The photos would be shown one by one until the number of rest photos to be shown reaches zero. Of course, efficient and single Jack would always choose “yes”.
When viewing photos, Jack would have a “fake impression point” on every photo, which is not accurate. To calculate the “true impression point” of one photo, Jack would recall the “fake impression point” of every previous photo whose “fake impression point” is larger than this photo, and regard the smallest “fake impression point” of them as the “true impression point” of this photo. Jack would like to sum the “true impression point” of all photos as the outcome of his effort.
Note that if such a larger “fake impression point” does not exist, the “true impression point” of this photo is zero.
示例1 输入 4 2 1 4 3 输出 6
超时代码
#include<stdio.h>
int cb[100009];
int main()
{
int n;
scanf("%d",&n);
{
long long ans = 0;
int min = 0;
for(int i=0 ; i<n ; i++){
scanf("%d",&cb[i]);
min = 99991177;
int qq = 0;
for(int j=0 ; j<i ; j++){
if(cb[j] > cb[i] && min > cb[j]){
min = cb[j];
}
}
if(min == 99991177){
min = 0;
}
ans += min;
}
printf("%lld\n",ans);
}
}
通过代码
#include<bits/stdc++.h>
using namespace std;
set<int>cb;
int main()
{
int n;
long long ans = 0;
cb.clear();
scanf("%d",&n);
for(int i=0 ; i<n ; i++){
int q;
scanf("%d",&q);
if(cb.upper_bound(q) != cb.end())
ans += *cb.upper_bound(q);
cb.insert(q);
}
printf("%lld\n",ans);
}
解释
使用STL中的set集合即可很快过题
头文件: #include<set>
简单用法:
- clear() 删除set容器中的所有的元素
- empty() 判断set容器是否为空
- begin() 返回set容器的第一个元素的地址
- size() 返回当前set容器中的元素个数
- end() 返回指向容器最后一个数据单元+1的指针,如果我们要输出最后一个元素的值应该是 *(—c.end());
set中有这样一个函数:
- upper_bound(int x) 返回容器中第一个比x大的数字的地址,找不到则返回end()
集合还有着元素不重复,并且元素自行升序排列的特点
题目思路: 每次输入的时候查找第一个比x大的数字,有则加到ans,无论有或者没有都加入集合,循环到结尾后输出ans即可