第一题:玩具
题目描述
有 n 个玩具,第 i 个玩具的价格是 ai 元,超市里搞促销活动,购买 2 个玩具即可免单其中价格较低的一个,价格相等也免单其中一个。牛牛想买下所有玩具,至少需要花多少元?
输入描述:
第一行一个正整数 n(1≤n≤106)。
第二行 n 个正整数,第 i 个表示 ai(1≤ai≤109)。
输出描述:
输出一个数表示答案
输入
3 1 2 3
输出
4
说明
第二个和第三个一起买,花 3 元,再花 1 元买下第一个,合计 4 元。
每次选取最大两个数即可,price加上最大的那个价格即可
#include<iostream>
#include<algorithm>
using namespace std;
const int N = 1000010;
typedef long long LL;
int a[N];
int n;
int main(){
cin>>n;
for(int i = 1; i <= n; i++) cin>>a[i];
sort(a + 1, a + 1 + n);
int l = n - 1, r = n;
LL price = 0;
while(l >= 1 || r >= 1){
if(l < 1){
price += a[r];
break;
}
int x = a[l], y = a[r];
if(x == y){
price += x;
l-= 2, r -= 2;
continue;
}
else{
price += max(x, y);
l -= 2, r -= 2;
continue;
}
}
cout<<price<<endl;
return 0;
}
这样写更简单
#include<iostream>
#include<algorithm>
using namespace std;
const int N = 1000010;
typedef long long LL;
int a[N];
int n;
int main(){
cin>>n;
for(int i = 1; i <= n; i++) cin>>a[i];
sort(a + 1, a + 1 + n);
int l = n - 1, r = n;
LL price = 0;
for(int i = n; i >= 1; i -= 2){
price += a[i];
}
cout<<price<<endl;
return 0;
}