codeforces round499 div2 A. Stages

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/A7_RIPPER/article/details/81877362

这里写图片描述这里写图片描述这里写图片描述

题目大意:

给你n个小写字母表示的阶段,然后火箭需要其中的k个,这k个必须不相邻并且递增。每一个字母有一个重量,a是1吨,b是2吨。。。问最少多少吨。

解题思路:

贪心思想,既然求最小,那首先排序,然后“相邻”位置进行比较,注意这里的相邻是指可以满足条件的“相邻”字母,不是数组中的相邻,我们可以先把满足条件的字母保存下来,然后从它的位置以后继续比较。
代码如下:

#include<iostream>
#include<cstdio>
#include<fstream>
#include<set>
#include<cmath>
#include<cstring>
#include<string>
#include<map>
#include<vector>
#include<iomanip>
#include<cstdlib>
#include<list>
#include<queue>
#include<stack>
#include<algorithm>
#define inf 0x3f3f3f3f
#define MOD 1000000007
#define mem0(a) memset(a,0,sizeof(a))
#define mem1(a) memset(a,-1,sizeof(a))
#define meminf(a) memset(a,inf,sizeof(a))
#define HASHP 13331;
//map<int>::iterator it
typedef long long ll;
typedef unsigned long long ull;
using namespace std;
int main()
{
  std::ios::sync_with_stdio(false);
  cin.tie(0);
  //freopen("test.txt","r",stdin);
  //freopen("output.txt","w",stdout);
  int n,k;
  int  stage[60];
  cin>>n>>k;
  for(int i=0;i<n;i++)
  {
    char t;
    cin>>t;
    stage[i]=t-'a'+1;
  }
  bool flag=true;
  sort(stage,stage+n);
  int sum=stage[0],num=1,cur1=0,cur2=1;
  while(num<k)
  {
    if(stage[cur2]-stage[cur1]>=2)//满足条件
    {
      num++;//数量+1
      sum+=stage[cur2];//总重量和增加
      cur1=cur2;//更新当前比较位置
      cur2++;
    }
    else
    {
      cur2++;
      if(cur2>=n)//遍历完也没有找到k个
      {
        flag=false;
        break;
      }
    }
  }
  if(flag)cout<<sum<<endl;
  else cout<<-1<<endl;
  return 0;
}

猜你喜欢

转载自blog.csdn.net/A7_RIPPER/article/details/81877362