安庆网站建设专业制,腾讯云轻量服务器,钢化网,唐山市城乡建设局网站个人学习记录#xff0c;代码难免不尽人意。 做了这么多题难得本题不看答案一遍过#xff0c;很是激动。 Shopping in Mars is quite a different experience. The Mars people pay by chained diamonds. Each diamond has a value (in Mars dollars M$). When making the pa… 个人学习记录代码难免不尽人意。 做了这么多题难得本题不看答案一遍过很是激动。 Shopping in Mars is quite a different experience. The Mars people pay by chained diamonds. Each diamond has a value (in Mars dollars M$). When making the payment, the chain can be cut at any position for only once and some of the diamonds are taken off the chain one by one. Once a diamond is off the chain, it cannot be taken back. For example, if we have a chain of 8 diamonds with values M$3, 2, 1, 5, 4, 6, 8, 7, and we must pay M$15. We may have 3 options:
Cut the chain between 4 and 6, and take off the diamonds from the position 1 to 5 (with values 3215415). Cut before 5 or after 6, and take off the diamonds from the position 4 to 6 (with values 54615). Cut before 8, and take off the diamonds from the position 7 to 8 (with values 8715). Now given the chain of diamond values and the amount that a customer has to pay, you are supposed to list all the paying options for the customer.
If it is impossible to pay the exact amount, you must suggest solutions with minimum lost. Sample Input 1: 16 15 3 2 1 5 4 6 8 7 16 10 15 11 9 12 14 13 Sample Output 1: 1-5 4-6 7-8 11-11 Sample Input 2: 5 13 2 4 5 7 9 Sample Output 2: 2-4 4-5 #includecstdio
#includeiostream
#includevector
#includealgorithm
#includestring
#includemap
#includecmath
using namespace std;
int num[100010];
int main(){int n,m;scanf(%d%d,n,m);for(int i0;in;i){scanf(%d,num[i]);}int i0,j0;int temp0;bool flagfalse;int cost1000000000;vectorpairint,int v;int count0;while(in||jn){
// cout i j endl;if(tempm){if(jn) break;tempnum[j];jmin(n,j1);}else if(tempm){flagtrue;printf(%d-%d\n,i1,j);if(j1n){temptemp-num[i]num[j];j;}else{jmin(n,j1);temptemp-num[i];} imin(n,i1);}else{if(tempcost){costtemp;v.clear();v.push_back(make_pair(i1,j));}else if(tempcost){v.push_back(make_pair(i1,j));}temp-num[i];imin(n,i1);}}if(!flag!v.empty()){for(int k0;kv.size();k){printf(%d-%d\n,v[k].first,v[k].second);}}return 0;
}
利用了《算法笔记》中讲述的“two points”思想设置了ij两个下标来从左到右遍历数组其中记录num[i]到num[j]的和temp判断temp和m的关系分为三种情况①如果temp小于m则让j如果j已经等于边界n则说明不可能再得到新结果了直接break。②如果temp等于m则此时i和j就是我们想要输出的结果直接输出然后让i和j都加一相应的temp减去num[i]加上num[j]的值。③如果temp大于m则让i相应的减去temp对应的值。