1044. Shopping in Mars (25)
来源:互联网 发布:知乎er是什么意思 编辑:程序博客网 时间:2024/06/03 16:00
1.使用尺取法,如果取得范围总和大于需要pay的,删掉头部
2.如果取得范围综合小于pay的,增加尾部
3.注意边界情况和没有相等的情况,细节可查看代码
4.利用一个minAns的变量进行记录答案数值
部分测试用例如下:
16 153 2 1 5 4 6 8 7 16 10 15 11 9 12 14 13 5 132 4 5 7 9 10 1 2 3 4 5 6 1 2 3 4 6 10 1 2 3 4 5 1 1 2 1 1 1 ans: 5-5 6-6 8-8 9-9 10-10 10 0 2 3 4 5 1 1 2 1 1 1 ans: 5-5 6-6 8-8 9-9 10-10 10 -1 2 3 4 5 1 1 2 1 1 1 ans: 5-5 6-6 8-8 9-9 10-10
#include <iostream>#include <stdio.h>#include <vector>#include <stack>#include <algorithm>#include <memory.h>#include <map>#include <set>#include "limits.h"using namespace std;/*16 153 2 1 5 4 6 8 7 16 10 15 11 9 12 14 13 5 132 4 5 7 9 10 1 2 3 4 5 6 1 2 3 4 6 10 1 2 3 4 5 1 1 2 1 1 1 ans: 5-5 6-6 8-8 9-9 10-10 10 0 2 3 4 5 1 1 2 1 1 1 ans: 5-5 6-6 8-8 9-9 10-10 10 -1 2 3 4 5 1 1 2 1 1 1 ans: 5-5 6-6 8-8 9-9 10-10 */bool cmp(const pair<int,pair<int,int>>&a,const pair<int,pair<int,int>>&b){ if(a.first<b.first) return true; else if(a.first==b.first&&a.second.first<b.second.first) return true; else return false;}int main(void){ int sum,pay; scanf("%d %d",&sum,&pay); vector<int> diamonds(sum); for(int i=0;i<sum;i++) { scanf("%d",&diamonds[i]); } int i=0,j=0; int value=diamonds[0];//默认输入的数组大于0 int minAns=INT_MAX; vector<pair<int,pair<int,int>>> ans(0); while(1) { if(value==pay&&i<=j) {//加入i<=j,避免出现2-1,6-4之类的,j小于i的情况 minAns=min(minAns,value); ans.push_back({value,{i+1,j+1}}); value-=diamonds[i++]; } else if(value>pay&&i<=j) {//加入i<=j,避免出现2-1,6-4之类的,j小于i的情况 if(value<=minAns) {//value>pay && value<=minAns,所以 pay<value<=minAns,minAns>pay minAns=value; ans.push_back({value,{i+1,j+1}}); } value-=diamonds[i++]; } else//value<pay { j++; if(j<diamonds.size()) value+=diamonds[j]; else break; } } sort(ans.begin(), ans.end(), cmp); for(int k=0;k<ans.size();k++) { if(ans[k].first==minAns) printf("%d-%d\n",ans[k].second.first,ans[k].second.second); else break; } return 0;}
0 0
- 1044. Shopping in Mars (25)
- 1044. Shopping in Mars (25)
- 1044. Shopping in Mars (25)
- 1044. Shopping in Mars (25)
- 1044. Shopping in Mars (25)
- 1044. Shopping in Mars (25)
- 1044. Shopping in Mars (25)
- 1044. Shopping in Mars (25)
- 1044. Shopping in Mars (25)
- 1044. Shopping in Mars (25)
- 1044. Shopping in Mars (25)
- 1044. Shopping in Mars (25)
- 1044. Shopping in Mars (25)
- 1044. Shopping in Mars (25)
- 1044. Shopping in Mars (25)
- 1044. Shopping in Mars (25)
- 1044. Shopping in Mars (25)
- 1044. Shopping in Mars (25)
- 为sourceinsight添加makefile、kconfig、*.S文件支持
- 11.3 公用对话框
- Linux下命令行显示当前全路径方法
- Android屏幕分辨率适配
- AFNetworking原理及常用操作
- 1044. Shopping in Mars (25)
- Java调用WebService接口实现发送手机短信验证码功能
- Android中build target,minSdkVersion,targetSdkVersion,maxSdkVersion概念区分
- Jedis连接池的使用
- 系统运维全面解析:技术、管理与实践——互动出版网
- 用SpriteBuilder简化"耕牛遍地走"的动画效果(四)
- Android应用开发错误库(上)
- SwipeRefreshLayout 仿IOS ,下拉弹回效果
- ios照片头信息的获取