贪心算法

最简单的贪心:有限个硬币组成A元,不存在贪心不能最小问题

	for(int i=5;i>=0;i++){
		use[i]=min(A/V[i],num[i]);
		A-=use[i]*V[i];
		}
	}

区间调度问题

告知每个任务的起始时间和终止时间,要完成尽可能多的任务,如何选择?

贪心方式:
开始最早:


用时最短:



结束最早:为什么正确?

1.如果是结束最早的,相同时间内已经完成的最多

2.如果是结束最短的,以后能完成的任务数量最多

<span style="color:#330000;">#include <iostream>
#include <algorithm>
using namespace std;
const int maxn=10005;
int order[maxn];
typedef struct{
	int st,et;
	int number;
}Task;
Task tasks[maxn];

bool compare(Task a,Task b){
	if(a.ed<b.st) return true;
	return false;
}
int main(int argc, char const *argv[])
{
	int N;
	cin>>N;
	for(int i=1;i<=N;i++){
		cin>>tasks[i].st>>tasks[i].ed;
		tasks[i].number=i;
	}
	sort(tasks+1,tasks+n+1,compare);
	int ans=1;
	int current=tasks[1];
	for(int i=2;i<=N;i++){
		if(tasks[i].st>current.ed){
			current=tasks[i];
			ans++;
		}

	}
	/* code */
	return 0;
}</span>

poj3617 字典序问题 挑战程序设计竞赛43

#include <iostream>
using namespace std;
const int maxn=2005;
char in[maxn];
char out[maxn];
int main(int argc, char const *argv[])
{
	int N;
	cin>>N;
	for(int i=1;i<=N;i++)
		cin>>in[i];
	int first=1;
	int last=N;
	int index=1;
	int next;
	int offset;
	bool flag;
	while(first!=last){
		if(in[first]<in[last]) next = first++;
		else if(in[first]>in[last]) next=last--;
		else{
		for(offset=1,flag = true;first+offset!=last-offset;offset++){
			if(in[first+offset]<in[last-offset]){ next=first++;flag=false; break;}
			else if(in[first+offset]>in[last-offset]){ flag=false;next=last--; break;}
		}
		if(flag)
			next=first++; 
		} 
		out[index++]=in[next];
	}
	out[index]=in[first];
	for (int i = 0; i < N; i++)
  		{
    		printf("%c", out[i]);
    		if (i % 80 == 79) printf("\n");
  		}
 	 if (N % 80) printf("\n");

	return 0;
}
如果不相等,肯定是取小的好,因为最前面的位应该尽量的小

如果相等,那么往下比较,如果从左接近比从右接近小,那么从左,比如CBDC,肯定是从左比较好.(CDFC也是一样的)


poj3069

怎么贪心?

从左边最小的点开始?

反例:1 11 15

同理,右边也不行

应该对于每个点xi,考虑x+ri内最大的点,这一点是肯定要选取的,然后再考虑下一个没有被覆盖的点,继续考虑xk+R


#include <iostream>
#include <algorithm>
using namespace std;
int R;
int N;
int cover;
const int maxn=1005;
int place[maxn];
int cnt;
const int INF=999999;
int main(int argc, char const *argv[])
{
	while(cin>>R>>N){
		cnt=0;
		cover=-1;
		if(R==-1) break;
		for(int i=0;i<N;i++){
			cin>>place[i];
		}
		place[N]=INF;
		sort(place,place+N);//对位置排序
		for(int i=0;i<N;i++){
			if(place[i]<=cover) continue;
			else{
				int j=i;
				while(place[j+1]<=place[i]+R) j++;
				cnt++;
				cover=place[j]+R;
			}
		}
		cout<<cnt<<endl;
	}
	return 0;
}
这里注意place[N]要设置成无穷大,不然可能发生数组越界

这里的j先判断后移动,是一种比较容易实现的代码

poj 3253

哈夫曼树 未解决

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值