贪心算法入门
完美字符串
#include <iostream>
#include <cstdlib>
#include <stdio.h>
#include <algorithm>
#include <math.h>
#include <string.h>
#include <queue>
#include <stack>
typedef long long ll;
using namespace std;
int cmp(int x,int y){return x>y;}
int main(){
char s[10010];
char b[30]={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
char b1[30]={'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
int c[30],sum=0;
int zzz=26;
memset(c,0,sizeof(c));
cin>>s;
for (int i = 0; i < strlen(s); i++)
{
for (int j = 0; j <=25; j++)
{
if(s[i]==b[j]||s[i]==b1[j]){
c[j]++;
}
}
}
sort(c,c+26,cmp);
for (int i = 0; i<=25; i++){
sum+=zzz*c[i];
zzz--;
}
printf("%d\n",sum);
return 0;
}
活动安排问题
思路 以末尾排序,开个结构体对末尾时间排序,然后从第一个开始“安排”能安上的安上 不能安上的拿走
#include <iostream>
#include <cstdlib>
#include <stdio.h>
#include <algorithm>
#include <math.h>
#include <string.h>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <set>
typedef long long ll;
using namespace std;
struct zz
{
int a;
int b;
}s[10010];
int cmp(struct zz p,struct zz q)
{
return p.b<q.b;
};
int main(){
int n;
int sum;
while(cin>>n){
sum=1;
for(int i=0;i<n;i++){
cin>>s[i].a>>s[i].b;
}
sort(s,s+n,cmp);
for(int i=0;i<n;i++){
//cout<<s[i].a<<" "<<s[i].b<<endl;
}
int text;
text =s[0].b;
for(int i=1;i<n;i++){
if(text<=s[i].a){
sum++;
//cout<<s[i].a<<" "<<s[i].b<<endl;
text=s[i].b;
}
}
cout<<sum<<endl;
}
return 0;
}
独木舟问题
思路 sort一边 从头尾开始往中间 加
#include <iostream>
#include <cstdlib>
#include <stdio.h>
#include <algorithm>
#include <math.h>
#include <string.h>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <set>
typedef long long ll;
using namespace std;
int main(){
int n,m,sum; // N 人数 M 承重
int a[10000];
cin>> n >> m;
sum=0;
for(int i=0;i<n;i++){
cin>>a[i];
}
sort(a, a+n);
int p,q;
p=0;
q=n-1;
while(p<=q){
if(a[p]+a[q]<=m){sum++;q--;p++;}
else{sum++;q--;}
}
printf("%d\n",sum);
return 0;
}