#include<iostream>#include<vector>#include<algorithm>usingnamespacestd;intcoinChangeGreedy(inttarget,vector<int>&coins){sort(coins.rbegin(),coins.rend());intnumCoins=0;for(intcoin:coins){while(target>=coin){target-=coin;numCoins++;}if(target==0){break;}}if(target>0){cout<<"No solution with the given coins!"<<endl;return-1;}returnnumCoins;}intmain(){vector<int>coins={1,5,10,25};inttarget=63;intminCoins=coinChangeGreedy(target,coins);if(minCoins!=-1){cout<<"Minimum number of coins: "<<minCoins<<endl;}return0;}
#include<iostream>#include<vector>#include<utility>#include<climits>usingnamespacestd;structEdge{intu,v,weight;};intfind(vector<int>&parent,inti){if(parent[i]==i){returni;}returnparent[i]=find(parent,parent[i]);}voidunion_set(vector<int>&parent,intu,intv){parent[find(parent,u)]=find(parent,v);}intsollin(constvector<vector<pair<int,int>>>&adjList){intn=adjList.size();intmst_weight=0;vector<int>parent(n);for(inti=0;i<n;++i){parent[i]=i;}intnum_components=n;while(num_components>1){vector<Edge>min_edge(n,{-1,-1,INT_MAX});for(intu=0;u<n;++u){for(constauto&edge:adjList[u]){intv=edge.first;intweight=edge.second;intu_component=find(parent,u);intv_component=find(parent,v);if(u_component!=v_component){if(weight<min_edge[u_component].weight){min_edge[u_component]={u_component,v_component,weight};}}}}for(constauto&edge:min_edge){if(edge.weight!=INT_MAX){intu_component=find(parent,edge.u);intv_component=find(parent,edge.v);if(u_component!=v_component){mst_weight+=edge.weight;union_set(parent,u_component,v_component);--num_components;}}}}returnmst_weight;}intmain(){vector<vector<pair<int,int>>>adjList={{{1,10},{2,6},{3,5}},{{0,10},{3,15}},{{0,6},{3,4}},{{0,5},{1,15},{2,4}}};intmst_weight=sollin(adjList);cout<<"Weight of the minimum spanning tree: "<<mst_weight<<endl;return0;}
#include<iostream>#include<queue>#include<vector>#include<unordered_map>#include<string>usingnamespacestd;structNode{charcharacter;intfrequency;Node*left;Node*right;Node(charcharacter,intfrequency,Node*left=nullptr,Node*right=nullptr):character(character),frequency(frequency),left(left),right(right){}};structCompareNode{booloperator()(constNode*a,constNode*b){returna->frequency>b->frequency;}};voidgenerateHuffmanCodes(Node*root,stringcode,unordered_map<char,string>&huffmanCodes){if(root==nullptr){return;}if(root->left==nullptr&&root->right==nullptr){huffmanCodes[root->character]=code;}generateHuffmanCodes(root->left,code+"0",huffmanCodes);generateHuffmanCodes(root->right,code+"1",huffmanCodes);}unordered_map<char,string>buildHuffmanCodes(conststring&input){unordered_map<char,int>frequencyMap;for(charc:input){++frequencyMap[c];}priority_queue<Node*,vector<Node*>,CompareNode>pq;for(constauto&entry:frequencyMap){pq.push(newNode(entry.first,entry.second));}while(pq.size()>1){Node*left=pq.top();pq.pop();Node*right=pq.top();pq.pop();Node*newNode=newNode('\0',left->frequency+right->frequency,left,right);pq.push(newNode);}Node*root=pq.top();unordered_map<char,string>huffmanCodes;generateHuffmanCodes(root,"",huffmanCodes);returnhuffmanCodes;}intmain(){stringinput="this is an example for huffman encoding";unordered_map<char,string>huffmanCodes=buildHuffmanCodes(input);cout<<"Huffman codes:"<<endl;for(constauto&entry:huffmanCodes){cout<<entry.first<<": "<<entry.second<<endl;}return0;}
#include<iostream>#include<vector>#include<algorithm>usingnamespacestd;structItem{intweight;intvalue;doublevaluePerWeight;Item(intweight,intvalue):weight(weight),value(value),valuePerWeight((double)value/weight){}};boolcompareItems(constItem&a,constItem&b){returna.valuePerWeight>b.valuePerWeight;}doublefractionalKnapsack(intcapacity,vector<Item>&items){sort(items.begin(),items.end(),compareItems);doublemaxValue=0.0;for(Item&item:items){if(capacity>=item.weight){maxValue+=item.value;capacity-=item.weight;}else{maxValue+=item.valuePerWeight*capacity;break;}}returnmaxValue;}intmain(){intcapacity=50;vector<Item>items={Item(10,60),Item(20,100),Item(30,120),};doublemaxValue=fractionalKnapsack(capacity,items);cout<<"Maximum value in knapsack: "<<maxValue<<endl;return0;}
#include<iostream>#include<vector>#include<algorithm>usingnamespacestd;structInterval{intstart;intend;Interval(intstart,intend):start(start),end(end){}};boolcompareIntervals(constInterval&a,constInterval&b){returna.end<b.end;}intintervalScheduling(vector<Interval>&intervals){sort(intervals.begin(),intervals.end(),compareIntervals);intcount=0;intlastEnd=-1;for(constInterval&interval:intervals){if(interval.start>=lastEnd){lastEnd=interval.end;++count;}}returncount;}intmain(){vector<Interval>intervals={Interval(1,4),Interval(3,5),Interval(0,6),Interval(4,7),Interval(3,8),Interval(5,9),Interval(6,10),Interval(8,11)};intmaxNonOverlappingIntervals=intervalScheduling(intervals);cout<<"Maximum number of non-overlapping intervals: "<<maxNonOverlappingIntervals<<endl;return0;}
贪心算法在拓扑排序中并不是直接应用的解决方法,但是可以通过贪心策略实现拓扑排序。拓扑排序主要应用于有向无环图(DAG,Directed Acyclic Graph)的顶点排序。在拓扑排序中,对于所有的有向边 (u, v),顶点 u 必须在顶点 v 之前。换句话说,拓扑排序中的顶点顺序要满足图中所有有向边的顺序要求。拓扑排序在诸如任务调度、编译器中的符号依赖处理等领域有广泛应用。
#include<iostream>#include<vector>usingnamespacestd;intminElementsToCoverInterval(vector<int>&arr,inttarget_start,inttarget_end){intn=arr.size();intstart=target_start;intcount=0;inti=0;while(start<=target_end&&i<n){intmax_cover=start;while(i<n&&arr[i]<=start){max_cover=max(max_cover,arr[i]+1);i++;}if(max_cover==start){// 无法覆盖更多区域return-1;}start=max_cover;count++;}if(start<=target_end){// 无法覆盖整个目标区间return-1;}returncount;}intmain(){vector<int>arr={1,3,5,7,9};inttarget_start=2;inttarget_end=16;intcount=minElementsToCoverInterval(arr,target_start,target_end);if(count==-1){cout<<"Cannot cover the whole interval."<<endl;}else{cout<<"Minimum elements to cover the interval: "<<count<<endl;}return0;}