练题记录
题目链接:csp模拟练习202012-02
采用二重循环O(n²)最多只能得到70分
#include<iostream>
#include<vector>
#include<set>
#include<algorithm>
using namespace std;
//predict theta:0 1 3 5 7 y<theta 0 y>= theta 1
// predict == result theta=0
//6
//y result predict
//0 0 1 4
//1 0 1
//1 1 1
//3 1 1
//5 1 1
//7 1 1
int main()
{
int m;
vector<int> y,result,sum;
set<int> theta;
cin >> m;
for(int i=0;i<m;i++){
int a,b;
cin >> a >> b;
y.push_back(a);
result.push_back(b);
theta.insert(a);
}
// for(set<int>::iterator it=theta.begin();it!=theta.end();it++) //使用迭代器进行遍历
// {
// cout << *it;
// }
for(set<int>::iterator it=theta.begin();it!=theta.end();it++){
int flag=0;
// cout << "theta:" << *it << endl;
for(int j=0;j<m;j++){
int predict = 0;
if(y[j]>=*it) predict=1;
else predict=0;
if(predict==result[j]){
flag++;
}
// cout << "predict: " << predict << " " << "result:" << result[j] << endl;
}
sum.push_back(flag);
// cout << flag << endl;
}
int _max = *max_element(sum.begin(),sum.end());
// cout << _max << endl;
vector<int> set2vec,ans;
set2vec.assign(theta.begin(),theta.end());
for(int i=0;i<sum.size();i++){
if(sum[i]==_max) ans.push_back(set2vec[i]);
}
cout << *max_element(ans.begin(),ans.end()) << endl;
return 0;
}
算法学的菜,看了好多大佬的博客后终于看明白了
#include <algorithm>
#include <iostream>
#define N 100000
using namespace std;
typedef struct
{
int y;
int result;
}Point;
bool cmp(Point a, Point b)
{ //结构体排序规则 :默认按属性y升序排序,当属性y值相等时 按result排序 (>:降序 <:升序)
if (a.y == b.y)
{
return a.result < b.result;
}
return a.y < b.y;
}
int main(){
Point a[N+5];
int zeros = 0;
int ones = 0;
//保存可信度最大值,当前阈值y可信度,可信度最大的阈值
int max = 0,temp_max = 0,index = 0, index, n;
cin >> n;
for (int i = 0; i < n;i++){
cin >> a[i].y >> a[i].result;
//统计当前所有predict 为1的个数 作为排序后最小阈值的最大可信度
if(a[i].result==1){
ones++;
}
}
sort(a, a + n, cmp);
max = zeros + ones;
index = a[0].y;//最佳阈值 初值
for (int i = 1; i < n;i++){
/* 往前判断 如阈值为0(或最小值)时 ,result应该全为 1 才能 与预测值相等,即可信度
如样例1(阈值:0 1 3 5 7) 阈值为0时 1的个数为4
阈值为1时 则只需要在阈值0的可信度基础上作判断
也就是[1,3,5,7]result=1 而 0的result=0时才是可信的
所以当前阈值的前一个result(0)=0 zero+1 =1
temp_max = 1+4=5>4 更新最佳阈值可信度=5 index更新记录最佳阈值 a[i].y
*/
if(a[i-1].result==0){
zeros++;
}
/*
同上 当遍历到第三个节点 1 1时, a[2].result(1)=0 所以 zero+1=2
但是 阈值1的最大值在上一个节点已经记录,所以不变
*/
else if (a[i - 1].result == 1)
{
ones--;
}
if(a[i].y>a[i-1].y){
temp_max = ones + zeros;
if(temp_max>=max){
max = temp_max;
temp_max = 0;
index = a[i].y;
}
}
}
cout << index << endl;
return 0;
}
先做预排序sort 快排效率为O(nlogn)