Codeforces Round #507 Div.2 B. Shashlik Cooking(思维)

版权声明:欢迎转载,若转载,请标明出处,如有错误,请指点,也欢迎大佬们给出优化方法 https://blog.csdn.net/Charles_Zaqdt/article/details/82468249

题目链接:http://codeforces.com/contest/1040/problem/B

       题意是有n串正面朝上的羊肉串,输出k表示每次可以将第i串羊肉串的i-k到i+k的羊肉串翻过来,问最少需要翻多少次可以将所有的羊肉串翻过来。

       思路是分情况讨论,当k等于0的时候肯定要一串一串翻,当k的值大于n的一半的时候直接翻中间的数就能全部翻过来了,剩下一种情况,只需要判断从哪开始翻就行了,看下代码想一下就好了,不是很难。


AC代码:

#include <bits/stdc++.h>
#define maxn 10005
using namespace std;
int pre[maxn];
int n,k;

int main()
{
  scanf("%d%d",&n,&k);
  int ans;
  if(k == 0){
    ans = n;
    for(int i=1;i<=n;i++){
      pre[i] = i;
    }
  }
  else if(n <= (2 * k + 1)){
    ans = 1;
    pre[1] = n / 2 + 1;
  }
  else if(n > (2 * k + 1)){
    if(n % (2 * k + 1) > k || n % (2 * k + 1) == 0){
      ans = 0;
      for(int i=k+1;i<=n;i+=(2*k+1)){
        pre[++ans] = i;
      }
    }
    else{
      ans = 0;
      for(int i=1;i<=n;i+=(2*k+1)){
        pre[++ans] = i;
      }
    }
  }
  printf("%d\n",ans);
  for(int i=1;i<=ans;i++){
    printf("%d%c",pre[i],i==ans?'\n':' ');
  }
  return 0;
}

猜你喜欢

转载自blog.csdn.net/Charles_Zaqdt/article/details/82468249
今日推荐