使用upper_bound簡化代碼(從[start,end-1]內找出第一個大於該值的地址)
方法1
完全參照https://www.cnblogs.com/ligen/p/4351417.html的思路及代碼
思路:
1.二分遍歷找出滿足條件的最小花費nears
2.二分遍歷枚舉下標i,輸出所有花費恰好爲最小花費nears的情況。
疑問
Q:判等條件爲什麼是sum[j-1]-sum[i]==s
A:因爲Upper_bound返回第一個大於該值的,不包括等於該值。
#include <iostream>
#include<cstdio>
#include<algorithm>>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
const int N = 100000+10;
int sum[maxn];
int n, s, nears = 1e8;
int main(int argc, char** argv) {
scanf("%d %d", &n, &s);
sum[0] = 0;
for(int i = 1; i <= n; i++){
scanf("%d", &sum[i]);
sum[i] += sum[i-1];
}
//sum下標:1-n
//找到所有情況裏花費的最小錢數
for(int i = 1; i <= n; i++){
//jj爲第一個和>=sum[i-1]+s的sum數組下標.即i-j的和滿足的條件
int* jj = upper_bound(sum+i, sum+n+1, sum[i-1]+s);
//從數組的begin位置到end-1位置二分查找 >= num的數字
//找到返回該數字地址,不存在則返回end
//通過返回地址-數組起始地址得到數字在數組中下標
int j = jj-sum;//j是數組下標
if(sum[j-1]-sum[i-1] == s){
nears = s;
break;
}else if(j <= n && sum[j] - sum[i-1] < nears){
nears = sum[j] - sum[i-1];
}
//j成功找到沒有越界(j<=n)且花費更小
//大了,
}
//然後再次二分查找出所有花費恰好爲nears的情況並輸出
for(int i = 1; i <= n; i++){
int* jj = upper_bound(sum+i, sum+n+1, sum[i-1]+nears);
int j = jj-sum;
if(sum[j-1]-sum[i-1] == nears){
printf("%d-%d\n", i, j-1);
}
}
return 0;
}
方法2:
思路
用vector數組ans保存pair<int,int>記錄i和j
由於upper_bound(sum+1, sum+1+n, sum[i-1]+m)只能返回第一個大於所給值的地址,導致就算能夠恰好花費m元,它返回的也是花費m元的下標的後一個下標,這個思路需要分情況討論,思維上需要縝密。
1.sum[j-1]-sum[i-1] == m :若從下標i開始可以找到恰好爲m
1)第一次找到恰好爲m的
清空vector數組,再push
2)不是第一次
直接往vector數組裏Push即可
2. j <= n&&sum[j]-sum[i-1] < nears :不能恰好爲m,但是找到了目前爲止更小的花費
3. j <= n && sum[j]-sum[i-1] == nears :不能恰好爲m,該花費正好和之前最小花費相同
#include <iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<vector>
#include<string>
#include <map>
#define LL long long
using namespace std;
typedef pair<int, int> pr;
const int maxn = 100000+5;
int sum[maxn];
vector<pr> ans;
int main(){
int n, m;
scanf("%d %d", &n, &m);
for(int i = 1; i <= n; i++){
int x;
scanf("%d", &sum[i]);
sum[i] += sum[i-1];
}
int nears = 1e8;
for(int i = 1; i <= n; i++){
//查找範圍爲[begin, end-1]
int* jj = upper_bound(sum+i, sum+n+1, sum[i-1]+m);
int j = jj-sum;//數組下標+1
//目前新的最小花費
if(sum[j-1]-sum[i-1] == m){
if(nears>m){
nears = m;
ans.clear();
ans.push_back(make_pair(i,j-1));
}else if(nears == m){
ans.push_back(make_pair(i,j-1));
}
}else if(j <= n && sum[j]-sum[i-1] < nears){
ans.clear();
ans.push_back(make_pair(i, j));
nears = sum[j] - sum[i-1];
}else if(j <= n && sum[j] - sum[i-1] == nears){
ans.push_back(make_pair(i, j));
}
}
for(int i = 0; i < ans.size(); i++){
printf("%d-%d\n", ans[i].first, ans[i].second);
}
return 0;
}