贪心算法QwQ

P2240 【深基12.例1】部分背包问题

答案

cpp 复制代码
#include <bits/stdc++.h>
using namespace std;

struct Node{//金币结构体
    int w,v;
}a[110];

int read(){
    int x=0,f=1;
    char c=getchar();
    while(c<'0'||c>'9'){
        if(c=='-')f=-1;
        c=getchar();
    }
    while(c>='0'&&c<='9'){
        x=x*10+c-'0';
        c=getchar();
    }
    return x*f;
}

bool cmp(Node aa,Node bb){
    return aa.v*bb.w>aa.w*bb.v;
    //按性价比从高到低排序,为防止精度问题直接交叉相乘
}

int main(){
    int n=read(),m=read();
    double ans=0;
    for(int i=1;i<=n;i++){
        a[i].w=read(),a[i].v=read();
    }
    sort(a+1,a+n+1,cmp);
    for(int i=1;i<=n;i++){
        if(a[i].w<=m){
            ans+=a[i].v;
            m-=a[i].w;
        }
        else{
            ans+=a[i].v*m*1.0/(a[i].w*1.0);
            //*1.0强转double
            break;
        }
    }
    printf("%.2lf",ans);
    return 0;
}

P1223 排队接水

答案

cpp 复制代码
#include <bits/stdc++.h>
using namespace std;

struct Node {
    int n, t;
} a[1010];

// 按照接水时间从小到大排序
bool cmp(Node aa, Node bb) {
    return aa.t < bb.t;
}

// 读入函数
int read() {
    int x = 0, f = 1;
    char c = getchar();
    while (c < '0' || c > '9') {
        if (c == '-') {
            f = -1;
        }
        c = getchar();
    }
    while (c >= '0' && c <= '9') {
        x = x * 10 + c - '0';
        c = getchar();
    }
    return x * f;
}

int main() {
    int N = read();
    double ans = 0;

    // 读取每个人的接水时间
    for (int i = 1; i <= N; i++) {
        a[i].t = read();
        a[i].n = i;
    }

    // 对接水时间从小到大排序
    sort(a + 1, a + N + 1, cmp);

    // 输出排队顺序
    for (int i = 1; i <= N; i++) {
        printf("%d ", a[i].n);
        if (i < N) { // 前面的所有人需要等待
            ans += a[i].t * (N - i);
        }
    }
    printf("\n");

    // 计算平均等待时间并输出
    printf("%.2lf\n", ans / N);

    return 0;
}

P1803 凌乱的yyy / 线段覆盖

答案

cpp 复制代码
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
int N;

struct act{
	int start;
	int end;
}a[1000010]; 

bool cmp(act a,act b){
	return a.end<b.end;
}

int greedy(){
	int num=1,i=0;
	for(int j=1;j<=N;j++){
		if(a[j].start>=a[i].end){
			i=j;
			num++;
		}
	}
	return num;
}

int main(){
	scanf("%d",&N);
	for(int i=0;i<N;i++){
		scanf("%d%d",&a[i].start,&a[i].end);
	}
	sort(a,a+N,cmp);
	int ans=greedy();
	printf("%d\n",ans);
	return 0;
}
相关推荐
淮北49437 分钟前
STL学习(十一、常用的算数算法和集合算法)
c++·vscode·学习·算法
糖葫芦君41 分钟前
玻尔兹曼分布与玻尔兹曼探索
人工智能·算法·机器学习
摸鱼仙人~43 分钟前
Redis 数据结构全景解析
数据结构·数据库·redis
AA陈超3 小时前
虚幻引擎5 GAS开发俯视角RPG游戏 #06-11:游戏后效果执行
c++·游戏·ue5·游戏引擎·虚幻
花火|6 小时前
算法训练营day37 动态规划⑤ 完全背包 518. 零钱兑换 II、 377. 组合总和 Ⅳ、70. 爬楼梯 (进阶)
算法·动态规划
Neil今天也要学习6 小时前
永磁同步电机无速度算法--脉振方波注入法
算法
小学生的信奥之路6 小时前
力扣1116题:用C++实现多线程交替输出零、偶数、奇数
c++·leetcode·多线程
绿炮火7 小时前
【MATLAB】(二)基础知识
开发语言·算法·matlab
老狼主7 小时前
MFC CChartCtrl编程
c++·mfc
88号技师7 小时前
2025年6月最新SCI-灰熊脂肪增长优化算法Grizzly Bear Fat Increase-附Matlab免费代码
开发语言·人工智能·算法·matlab·优化算法