贪心算法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;
}
相关推荐
运器12341 分钟前
【一起来学AI大模型】支持向量机(SVM):核心算法深度解析
大数据·人工智能·算法·机器学习·支持向量机·ai·ai编程
Zedthm1 小时前
LeetCode1004. 最大连续1的个数 III
java·算法·leetcode
神的孩子都在歌唱1 小时前
3423. 循环数组中相邻元素的最大差值 — day97
java·数据结构·算法
YuTaoShao1 小时前
【LeetCode 热题 100】73. 矩阵置零——(解法一)空间复杂度 O(M + N)
算法·leetcode·矩阵
眠りたいです2 小时前
Mysql常用内置函数,复合查询及内外连接
linux·数据库·c++·mysql
dying_man2 小时前
LeetCode--42.接雨水
算法·leetcode
笑鸿的学习笔记2 小时前
qt-C++语法笔记之Stretch与Spacer的关系分析
c++·笔记·qt
hardStudy_h3 小时前
C++——内联函数与Lambda表达式
开发语言·jvm·c++
vortex53 小时前
算法设计与分析 知识总结
算法
艾莉丝努力练剑3 小时前
【C语言】学习过程教训与经验杂谈:思想准备、知识回顾(三)
c语言·开发语言·数据结构·学习·算法