您的位置:首页 > 运维架构

PAT 1044. Shopping in Mars (25)

2015-01-02 22:09 316 查看
本题基本解决思路是:

从数组前往后搜索遍历,与M进行比较。

关键点在于当结果与M值不相同时,如何取得和M值相同的结果。

需要适当剪枝避免超时。

//1044. Shopping in Mars (25)
//
//本题基本解决思路是:
//		从数组前往后搜索遍历,与M进行比较。
//		关键点在于当结果与M值不相同时,如何取得和M值相同的结果。
//		需要适当剪枝避免超时。

#include<iostream>
#include <functional>
#include <vector>
using namespace std;

int N, M;
int D[100005] = {0};

typedef struct Seg
{
int s;
int e;
}Seg;

int main()
{
#ifdef ONLINE_JUDGE
#else
freopen("D:\\1.txt", "r", stdin);
#endif

scanf("%d %d", &N, &M);

int i;
for (i = 0;i<N;i++)
{
scanf("%d", &D[i]);
}

i = 0;
int j = 0;
int CurrTotalD = 0;

int MinM = 1<<30;
vector<Seg> result;
vector<Seg> MinMResult;

while(i < N)
{
if (CurrTotalD < M)
{
if (j >= N)
{
break;
}
CurrTotalD += D[j];
j++;
continue;
}

Seg tmp;
tmp.s = i +1;
tmp.e = j;

if(CurrTotalD == M)
{
result.push_back(tmp);
}
else
{
if (result.size() == 0)
{
if (MinM > CurrTotalD)
{
MinM = CurrTotalD;
MinMResult.clear();
MinMResult.push_back(tmp);
}
else if(MinM == CurrTotalD)
{
MinMResult.push_back(tmp);
}
}
}

CurrTotalD -= D[i];
i++;
}

for (i = 0;i<result.size();i++)
{
printf("%d-%d\n", result[i].s, result[i].e);
}

if (result.size() == 0)
{
for (i = 0;i<MinMResult.size();i++)
printf("%d-%d\n", MinMResult[i].s, MinMResult[i].e);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: