结构体排序,重载运算符即可
bool operator <(const node a)const{
return a.weight < weight;
}
//
// main.cpp
// greedy_01
//
// Created by 陈冉飞 on 2019/12/15.
// Copyright © 2019 陈冉飞. All rights reserved.
//
#include
using namespace std;
#define maxn 10010
struct node{
int w,v;
double weight;
bool operator < (const node a)const{return a.weight < weight;}
}a[maxn];
int n,wtotal,ans = 0;
#include
int main(int argc, const char * argv[]) {
while (~scanf("%d%d",&n,&wtotal)) {
for (int i = 0; i < n; i++) scanf("%d%d",&a[i].v,&a[i].w),a[i].weight = a[i].v*1.0/a[i].w;
sort(a,a+n);
// for (int i = 0; i < n; i++) printf("%lf ",a[i].weight);
for (int i = 0; i < n && wtotal >= a[i].w; i++) {
ans += a[i].v;
wtotal -= a[i].w;
}
printf("%d\n",ans);
}
return 0;
}
//
// main.cpp
// dfs_01
//
// Created by 陈冉飞 on 2019/12/15.
// Copyright © 2019 陈冉飞. All rights reserved.
//
#include
using namespace std;
#define maxn 10010
int n,wtotal,w[maxn],v[maxn],ans = 0,tem = 0;
#include
#define cl(a,b) memset(a,b,sizeof(a))
void dfs(int t){
if (t == n) {
if (tem > ans) ans = tem;
return;
}
if (wtotal >= w[t]) {
tem += v[t];wtotal -= w[t];
dfs(t+1);
tem -= v[t];wtotal += w[t];
}
dfs(t+1);
}
int main(int argc, const char * argv[]) {
while (~scanf("%d%d",&n,&wtotal)) {
//init
cl(w,0);cl(v, 0);ans = 0;tem = 0;
for (int i = 0; i < n; i++) scanf("%d%d",&v[i],&w[i]);
dfs(0);
printf("%d\n",ans);
}
return 0;
}
本来很简单的一个简单的bfs,但是由于马虎太菜了,debug半天就是没有发现输入的时候0-n写成了1-n,然后就一直少一组数据,然后gg。 开结构体放到队列中,通过队列取front来达到按层次遍历,然后通过index、wsum、vsum三个结构体中的属性分别记录索引(也是深度,用来判断时候应该跳出去判断)、到这个物品之前所占用的总空间、到这个物品之前的总价值
//
// main.cpp
// bfs_01
//
// Created by 陈冉飞 on 2019/12/15.
// Copyright © 2019 陈冉飞. All rights reserved.
//
#include
using namespace std;
#include
struct node{
int index,wsum,vsum;
node(int i,int w,int v):index(i),wsum(w),vsum(v){}
};
queue<node> q;
#define maxn 10010
int n,wtotal,w[maxn],v[maxn],ans = 0;
void bfs(){
q.push(node(-1, 0, 0));
int a = 1;
while (!q.empty()) {
if ((a ++) >=100 ) break;
node temnode = q.front();
q.pop();
if (temnode.index == n-1 && ans < temnode.vsum) ans = temnode.vsum;
if (temnode.index+1 < n) {
if (temnode.wsum + w[temnode.index+1] <= wtotal) q.push(node(temnode.index+1,temnode.wsum+w[temnode.index+1], temnode.vsum+v[temnode.index+1]));
//don't choose
q.push(node(temnode.index+1,temnode.wsum,temnode.vsum));
}
}
}
int main(int argc, const char * argv[]) {
while (~scanf("%d%d",&n,&wtotal)) {
ans = 0;
for (int i = 0; i < n; i++) scanf("%d%d",&v[i],&w[i]);
bfs();
printf("%d\n",ans);
}
return 0;
}