【作业】 贪心算法

T1

cpp 复制代码
#include <iostream>
#include <algorithm>
using namespace std;
struct soider{
	int B;
	int J;
};
bool cmp(soider a,soider b){
	return a.J>b.J;
}
soider a[1000010];
int n;
void solve(int n,int num){
	for(int i=0;i<n;i++){
		scanf("%d%d",&a[i].B,&a[i].J);
	}
	sort(a+0,a+n,cmp);
	int t=0;
	int work=0;
	for(int i=0;i<n;i++){
		t+=a[i].B;
		if(work>a[i].B)
			work-=a[i].B;
		else 
			work=0;
		work=max(a[i].J,work);
	}
	printf("Case %d:%d\n",num,t+work);
}
int main(){
	scanf("%d",&n);
	int cnt=1;
	while(n>0){
		solve(n,cnt);cnt++;
		scanf("%d",&n);
	}
	
	return 0;
}

时间复杂度约为

T2

cpp 复制代码
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
struct soider {
	double l;
	double r;
};//用这个名字是因为省事

bool cmp(soider a, soider b) {
	return a.l < b.l;
}
int d;
soider a[1000010];
int n;//[x-sqrt(d*d-y*y),x+sqrt(d*d+y*y)]
void solve(int num) {

	scanf("%d", &d);
	for (int i = 0; i < n; i++) {
		int x;
		int y;
		scanf("%d%d", &x, &y);

		if (d * d - y * y < 0) {
			cout << "-1" << endl;
			return;
		}
		a[i].l = x - sqrt(d * d - y * y);
		a[i].r = x + sqrt(d * d - y * y);
		//cout << 'l' << a[i].l << endl;
		//cout << 'r' << a[i].r << endl;

	}
	sort(a + 0, a + n, cmp);
	double p = a[0].r;
	int cnt = 1;
	int i = 0;
	while (p <= a[n - 1].r && i < n) {
		//cout<<"p:"<<p<<endl;
		while (a[i].l <= p) {
			i++;
			//cout <<i<< " l " << a[i].r << endl;
			//cout <<i<< " r " << a[i].r << endl;
		}
		p = a[i].r;
		cnt++;
	}
	cout << cnt << endl;
}
int main() {
	scanf("%d", &n);


	solve(n);



	return 0;
}

时间复杂度约为

相关推荐
天若有情6732 小时前
循环条件隐藏陷阱:我发现了「同循环双条件竞态问题」
c++·学习·算法·编程范式·while循环··竞态
j_xxx404_2 小时前
C++算法:前缀和与哈希表实战
数据结构·算法·leetcode
We་ct2 小时前
LeetCode 22. 括号生成:DFS回溯解法详解
前端·数据结构·算法·leetcode·typescript·深度优先·回溯
mit6.8242 小时前
tabbi风波|开源协议
算法
是梦终空1162 小时前
C++中的职责链模式变体
开发语言·c++·算法
仰泳的熊猫3 小时前
题目2270:蓝桥杯2016年第七届真题-四平方和
c++·算法·蓝桥杯
CoovallyAIHub3 小时前
CVPR 2026 | VisualAD:去掉文本编码器,纯视觉也能做零样本异常检测
算法·架构·github
CoovallyAIHub3 小时前
东南大学提出 AutoIAD:多 Agent 驱动的工业异常检测自动化框架
算法·架构·github
ccLianLian3 小时前
算法·字符串
算法·哈希算法