查找和贪心问题

1.查找问题

1.1字符串查找(map函数应用)

题目描述

注意map函数的应用,

#include<bits/stdc++.h>
using namespace std;

struct student{
	string num;              //为什么这里只能用string,而不能用char num[10]?; 
	char name[10];
	char sex[10];
	int age;
}; 

int main(){
	int n,q;                 //输入n个学生的信息,输出m个学生的信息
	map<string,student>m;    //注意map函数的定义方法
	while(~scanf("%d",&n)){
		for(int i=0;i<n;i++){
			student a;
			cin>>a.num>>a.name>>a.sex>>a.age;
			m[a.num]=a;      //结构体中的一个成员对应整个结构体 
		} 
		scanf("%d",&q);
		for(int i=0;i<q;i++){  
	        string num;  
	        cin>>num;  
	        if((m.find(num))!=m.end())//当所查找的关键key出现时,它返回数据所在对象的位置,如果沒有,返回值与end函数的值相同  
	            cout<<m[num].num<<" "<<m[num].name<<" "<<m[num].sex<<" "<<m[num].age<<endl;  
	        else  
	            cout<<"No Answer!"<<endl;  
	    }
    } 
    return 0;
}

core code


map<string,student>m;    //注意map函数的定义方法
m[a.num]=a;      //结构体中的一个成员对应整个结构体 
if((m.find(num))!=m.end())//当所查找的关键key出现时,它返回数据所在对象的位置,如果沒有,返回值与end函数的值相同  

未解决的问题:

struct student{
	string num;              //为什么这里只能用string,而不能用char num[10]?; 
	char name[10];
	char sex[10];
	int age;
}; 

1.2 动态查找问题(map函数应用)

题目详情

源代码:

#include<bits/stdc++.h>
using namespace std;

int main(){
	int n;
	scanf("%d",&n);
	map<int,int>m;
	for(int i=0;i<n;i++){
		int x;
		scanf("%d",&x);  //x表示输入的数字,m[x]表示x在表中出现的次数 
		m[x]++;
	}
	int q;
	scanf("%d",&q);
	for(int i=0;i<q;i++){
		int y;
		scanf("%d",&y);
		if(m.find(y)!=m.end()) printf("find\n");
		else{
			printf("no\n");
			m[y]++;        //将y元素添加到m中 
		} 
	} 
	return 0;
} 

core code:

m[x]++;//这里既让x存在了m的表中,也标记了x在表中出现的次数

未做的题目:

练习题目:(用map函数练习)

1177 查找学生信息

1388 查找1

1387 查找 - 北邮

1383 查找第K小数

2.贪心算法

狭义上讲就是求几个数中的最大值,即如果有三张纸币,10元,3元,2元,就选10元的纸币,这就是贪心。

喝饮料问题

源代码:

#include<bits/stdc++.h>
using namespace std;

struct drink{
    
    
	double m,w;    //m表示容量,w表示价格 
};
struct drink a[50]; 

bool cmp(drink a,drink b){
    
    
	return (a.m/a.w)<(b.m/b.w);
}                            //注意cmp的使用,定义结构体用的drink 

int main(){
    
    
	int n,x;
	while(~scanf("%d%d",&x,&n)){
    
    
		if(x==(-1)&&n==(-1))  break;
		for(int i=0;i<n;i++){
    
    
			scanf("%lf%lf",&a[i].m,&a[i].w);
		}
		sort(a,a+n,cmp);
		double left=x;//买了i瓶饮料,剩余的钱 
		double totalml=0;//总共买的ml数 
		for(int i=0;i<n;i++){
    
    
			if(left>a[i].w) {
    
    
				totalml+=a[i].m;
//				printf("总共能买:%.3f\n",totalml);
				left-=a[i].w;
//				printf("钱还剩下:%.3f\n",left);
			}
			else if(left<=a[i].w||left>0) {
    
    
				totalml+=left/(a[i].m/a[i].w);
			    break;
			}
//			if(left!=0){
    
    
//				printf("%.3f\n",totalml);
//			}
		}
		printf("%.3f\n",totalml);
	} 
	return 0;
}

猜你喜欢

转载自blog.csdn.net/be_stronger/article/details/113099996