题目链接:http://pat.zju.edu.cn/contests/pat-a-practise/1044
// 折半查找
// 参考了孙佰贵的代码
// http://blog.csdn.net/sunbaigui/article/details/8656955
#include <stdio.h>
#include <iostream>
#include <vector>
#define SIZE 100000+10
using namespace std;
int sum[SIZE];
int n, m;
void Input()
{
scanf("%d%d", &n, &m);
int i, t;
sum[0]=0;
for(i=1; i<=n;i++)
{
scanf("%d", &t);
sum[i] = sum[i-1]+t;
}
return ;
}
int FindBest(int i)
{
int l = i, h = n;
while(l<h)
{
int mid = (l+h)/2;
if(sum[mid]-sum[i-1] >= m)//注意[i,j]的和的计算
{
h = mid;
}
else
{
l = mid+1;
}
}
return h;
}
int main()
{
#ifdef ONLINE_JUDGE
#else
freopen("E:\\in.txt", "r", stdin);
#endif
Input();
int best=-1, i;
vector<pair<int,int> > v;
for(i = 1; i <= n; i++)
{
int end = FindBest(i);
int tempsum = sum[end]-sum[i-1];
if(best == -1 || tempsum>=m && tempsum<best)
{
best=tempsum;
v.clear();
v.push_back(make_pair(i,end));
}
else if(best != -1 && tempsum == best)
{
v.push_back(make_pair(i,end));
}
}
//output
for(i=0; i < v.size(); i++)
{
printf("%d-%d\n", v[i].first, v[i].second);
}
return 0;
}
// 存在超时,2个测试点。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
#include <iostream>
#include <string>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <algorithm>
#define SIZE 100000+10
using namespace std;
struct Node
{
int start;
int end;
int sum;
};
Node buf[SIZE];
int d_list[SIZE];
int n, m;
bool cmp(Node a, Node b)
{
if( a.sum != b.sum)
{
return a.sum<b.sum;
}
else
{
return a.start <b.start;
}//确保稳定排序
}
void Input()
{
scanf("%d%d", &n, &m);
int i;
for(i=1; i<=n; i++)
{
scanf("%d", &d_list[i]);
}
}
void Calc()
{
int i;
for(i=1; i<=n; i++)
{
//init
buf[i].start=i;
buf[i].end=i;
buf[i].sum=d_list[i];
if(d_list[i]<m)
{
int j, sum=d_list[i];
for(j=i+1; j<=n; j++)
{
sum += d_list[j];
if(sum >= m)
{
buf[i].end=j;
buf[i].sum=sum;
break;
}
}//找到序列的尾
}
}// 暴力每个节点
}
void Output()
{
int min=1<<30;
bool flag = false;
sort(buf+1, buf+n+1, cmp);
int i;
for(i=1; i<=n; i++)
{
if(buf[i].sum == m)
{
printf("%d-%d\n", buf[i].start, buf[i].end);
flag = true;
}
else if(buf[i].sum > m)
{
min = buf[i].sum;
break;
}
}
if(flag == false)
{
for(i=1; i<=n; i++)
{
if(buf[i].sum == min)
{
printf("%d-%d\n", buf[i].start, buf[i].end);
}
else if(buf[i].sum > min)
{
break;
}
}
}
return ;
}
int main()
{
#ifdef ONLINE_JUDGE
#else
freopen("E:\\in.txt", "r", stdin);
#endif
Input();
Calc();
Output();
return 0;
}