【倒计时6 day 28/155】
第十二章 贪心法
1038 Recover the Smallest Number 排成最小的数字
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
bool cmp(string a,string b){
string str1,str2;
str1=a+b;
str2=b+a;
if(str1<str2){
return true;
}
return false;
}
int main(){
int N;
cin>>N;
vector<string> v;
string temp;
for(int i=0;i<N;i++){
cin>>temp;
v.push_back(temp);
}
sort(v.begin(),v.end(),cmp);
string res;
for(int i=0;i<N;i++){
res+=v[i];
}
int k = 0;
while (k + 1 < res.size() && res[k] == '0') k ++ ;
cout << res.substr(k) << endl;
return 0;
}
1070 Mooncake 月饼
难点:根据性价比排序优先级
#include<iostream>
#include<algorithm>
#define MaxN 1010
using namespace std;
struct Node1{
double level;
double amount;
double price;
bool operator<(const Node1& t){
if(level>t.level){
return true;
}
return false;
}
}Node[MaxN];
int main(){
int N,D;
scanf("%d%d",&N,&D);
for(int i=0;i<N;i++){
scanf("%lf",&Node[i].amount);
}
for(int i=0;i<N;i++){
scanf("%lf",&Node[i].price);
}
for(int i=0;i<N;i++){
Node[i].level=Node[i].price/Node[i].amount;
}
sort(Node,Node+N);
int weight=D;
double res=0;
for(int i=0;i<N;i++){
if(weight<=0){
break;
}
if(Node[i].amount>=weight){
res+=weight*Node[i].level;
weight=0;
}else{
res+=Node[i].price;
weight-=Node[i].amount;
}
}
printf("%.2lf\n",res);
return 0;
}
1113 Integer Set Partition 整数集合划分
一直以为231那里有坑,要当做串来做…发现没有必要
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main(){
int N,temp;
scanf("%d",&N);
vector<int> v;
for(int i=0;i<N;i++){
cin>>temp;
v.push_back(temp);
}
sort(v.begin(),v.end());
int s1=0,s2=0;
for(int i=0;i<(N/2);i++){
s1+=v[i];
}
for(int i=(N/2);i<N;i++){
s2+=v[i];
}
printf("%d %d\n",N%2,s2-s1);
return 0;
}