如下代码可对结构体数组中的元素进行排序,也差很少算是一个小小的模板了吧node
#include<iostream> #include<algorithm> using namespace std; struct node { int x; int y; bool operator<(const node &a) const//此操做是对操做符"<"进行重构 { return x < a.x;//对结构体数组x进行从大到小排序 // return y > a.y;//对结构体数组y进行从大到小排序 } }s[100]; //bool cmp(int x,int y)//这个重构函数不能用在结构体数组中 //{ // return x > y; //} int main() { int n; cin >> n; for(int i = 0;i < n;i++) cin >> s[i].x >> s[i].y; sort(s,s+n); for(int i = 0;i < n;i++) cout << s[i].x << " " << s[i].y << endl; cout << endl; return 0; }
运行结果:ios
也能够这样数组
#include<iostream> #include<algorithm> using namespace std; struct node { int x; int y; bool operator<(const node &a) const { return x > a.x; } }s[100]; bool cmp(node m,node n) { m.x < n.x; } int main() { int n; cin >> n; for(int i = 0;i < n;i++) cin >> s[i].x >> s[i].y; sort(s,s+n); for(int i = 0;i < n;i++) cout << s[i].x << " " << s[i].y << endl; cout << endl; return 0; }
对优先队列的应用,POJ2431是一个很好的题目,此题用了优先队列+贪心函数
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 29720 | Accepted: 8212 |
Descriptionui
Inputthis
Outputspa
Sample Inputrest
4 4 4 5 2 11 5 15 10 25 10
Sample Outputcode
2
Hintblog
Source
#include<iostream> #include<algorithm> #include<queue> using namespace std; struct node { int dis; int fuel; bool operator<(const node &a) const//此重构操做,请参考上面的代码 { return dis > a.dis;//返回dis,说明是对dis这个数组进行排序操做 } }stop[10005]; priority_queue<int> que; int main() { int n,l,p; cin >> n; for(int i = 0;i < n;i++) cin >> stop[i].dis >> stop[i].fuel; cin >> l >> p; int ans = 0; sort(stop,stop + n);//对加油站距离dis数组进行从大到小排序 que.push(p);//队列自动从大到小排序,即排序汽油p int temp = 0; while(l > 0 && !que.empty())//卡车未到达终点而且卡车在当前汽油用完前有路过加油站 { ans++;//卡车停下加一次油计数器 l -= que.top();//加油,更新一次汽油用尽后距离终点的距离 que.pop();//删除已用的加油站的汽油 while(l <= stop[temp].dis && temp < n)//卡车距离终点的距离小于等于最近加油站的距离而且这个加油站的位置在终点加油站前面,这里假设终点也为一个加油站。//l <= stop[i].dis意思是卡车能通过离它最近的一个加油站,若是大于的话,说明卡车停下时没有加油站可加油 que.push(stop[temp++].fuel);//将通过的加油站压入优先队列,要使用的时候就取队头元素(队头中存的汽油最大) //若是通过加油站,则必定要将该加油站的可加油量添加到优先队列当中 }//temp++说明离卡车最近的加油站,卡车继续往前开,加油站点也依次日后,因此变量temp须要自增 if(l > 0)//若是卡车距离终点的距离还大于0的话,即经过不了终点 cout << "-1" << endl; else cout << ans - 1 << endl;//在起点深度时候记为一次加油,这里须要减去1 return 0; }
其中代码有详细的注释,但愿注释能加深理解
代码参考于:博客园-小小菜鸟