分析:二分法的使用,直接二重循环会超时,下面附上超时和AC的代码
MAX取8个9给我看半天测试点2一直过不去 真的服了,MAX取9个9就过了
1、超时代码:
#include <iostream>
#include<cstring>
#include<vector>
#include<stdio.h>
#include<queue>
#include<math.h>
#include<stack>
#include<algorithm>
#include<map>
#include<set>
#define MAX 999999999
typedef long long ll;
using namespace std;
int n,m;
int dia[100002];
int sum[100002];
vector<int>ans1;
vector<int>ans2;
int main()
{
cin>>n>>m;
for(int i = 1;i<=n;i++)
{
int x;
cin>>dia[i];
sum[i] = sum[i-1] + dia[i];
}
int flag = 0;
int mmin = MAX;
for(int i = 1;i<=n;i++)
{
for(int j = i;j<=n;j++)
{
if(sum[j] - sum[i] + dia[i] == m)
{
flag = 1;
ans1.push_back(i);
ans2.push_back(j);
continue;
}
if(sum[j] - sum[i] + dia[i] >=m && sum[j] - sum[i] + dia[i] <mmin)
mmin = sum[j] - sum[i] + dia[i];
}
}
if(flag == 0)
{
for(int i = 1;i<=n;i++)
{
for(int j = i;j<=n;j++)
{
if(sum[j] - sum[i] + dia[i] == mmin)
{
ans1.push_back(i);
ans2.push_back(j);
continue;
}
}
}
}
for(int i = 0;i<ans1.size();i++)
cout<<ans1[i]<<"-"<<ans2[i]<<endl;
return 0;
}
二分法:
#include <iostream>
#include<cstring>
#include<vector>
#include<stdio.h>
#include<queue>
#include<math.h>
#include<stack>
#include<algorithm>
#include<map>
#include<set>
#define MAX 999999999
typedef long long ll;
using namespace std;
int n,m;
int des[100001];
int s[100001];
vector<int>ans;
int main()
{
cin>>n>>m;
for(int i = 1;i<=n;i++)
{
int x;
cin>>x;
s[i] = s[i-1] + x;
}
int mmin = MAX;
for(int i = 1;i<=n;i++)
{
int left = i;
int right = n;
int mid;
while(left < right)
{
mid = (left + right) / 2;
int x = s[mid] - s[i-1];
if(x < m)
left = mid + 1;
else
right = mid;
}
des[i] = right;
int x = s[right] - s[i-1];
if(x >= m)
{
if(x < mmin)
{
mmin = x;
ans.clear();
ans.push_back(i);
}
else if(x == mmin)
ans.push_back(i);
}
}
for(int i = 0;i<ans.size();i++)
cout<<ans[i]<<"-"<<des[ans[i]]<<endl;
return 0;
}