poj 3276

      思路其实很简单,为了使所有牛都朝向前方,从左到右扫描每个牛,若这个牛朝后,则以这个牛为起点进行翻转,而翻转的区间长度从1到n进行枚举,从合法解中选取最小的就行了。那么为什么这样解是对的呢?首先,一个区间进行两次或两次以上翻转是没有意义的;其次,若得到解要对一些区间进行翻转,那么对这些区间的翻转顺序是不影响解的。因此问题就转变为求满足解的最小区间集合。

      但如果真按着上面的思路写,枚举长度一个循环,遍历牛的数组一个循环,翻转也需要一个循环,这样时间复杂度就是o(n^3)级别的了,会超时,不过还好翻转的时间可以优化。优化方法在于翻转时只记录下翻转信息,而不真的修改牛的数组(这样就减掉翻转所需循环了)。但这样我们怎么知道某头牛的状态呢?方法也很简单。

      用f[i]表示第i头牛是否进行了翻转,0表示没翻转,1表示翻转了。

      这样,在考虑第i头牛时,只要考虑前k-1个牛的f[i]之和是否为奇数,奇数则表明第i头牛的方向与初始方向相反,偶数则相同。这个操作是o(1)的,总的时间复杂度就就降至o(n^2)了。

    代码如下:

#include <cstdio>
#include <stack>
#include <set>
#include <iostream>
#include <string>
#include <vector>
#include <queue>
#include <list>
#include <functional>
#include <cstring>
#include <algorithm>
#include <cctype>
#include <string>
#include <map>
#include <iomanip>
#include <cmath>
#define LL long long
#define ULL unsigned long long
#define SZ(x) (int)x.size()
#define Lowbit(x) ((x) & (-x))
#define MP(a, b) make_pair(a, b)
#define MS(arr, num) memset(arr, num, sizeof(arr))
#define PB push_back
#define F first
#define S second
#define ROP freopen("input.txt", "r", stdin);
#define MID(a, b) (a + ((b - a) >> 1))
#define LC rt << 1, l, mid
#define RC rt << 1|1, mid + 1, r
#define LRT rt << 1
#define RRT rt << 1|1
#define BitCount(x) __builtin_popcount(x)
#define BitCountll(x) __builtin_popcountll(x)
#define LeftPos(x) 32 - __builtin_clz(x) - 1
#define LeftPosll(x) 64 - __builtin_clzll(x) - 1
const double PI = acos(-1.0);
const int INF = 0x3f3f3f3f;
using namespace std;
const double eps = 1e-5;
const int MAXN = 300 + 10;
const int MOD = 1000007;
const double M=1e-8;
const int N=1e5+10;
typedef pair<int, int> pii;
typedef pair<int, string> pis;
const int d[4][2]={{0,1},{0,-1},{-1,0},{1,0}};
int n,m,k,a[N],f[N];
int slove(int x)
{
    MS(f,0);
    int i,j,sum=0,ans=0;
    for (i=0;i+x<=n;i++) {
         if ((a[i]+sum)&1) {   // reverse if sum is odd
            ans++;
            f[i]=1;
            sum+=f[i];
         }
         if (i-x+1>=0) {
            sum-=f[i-x+1];
         }
    }
    for (;i<n;i++) {
        if ((a[i]+sum)&1) {   // 无解
            return -1;
        }
        if (i-x+1>=0) {
            sum-=f[i-x+1];
        }
    }
    return ans;
}
int main()
{
    int i,j;
    char c[2];
    while(~scanf("%d",&n))
    {
        MS(a,0);
        for (i=0;i<n;i++) {
            scanf("%s",c);
            if (c[0]=='F') a[i]=0;
            else a[i]=1;
        }
        k=1,m=n;
        for (i=1;i<=n;i++) {  // 枚举长度
            int cnt=slove(i);
            if (cnt>=0 && cnt<m) {
                m=cnt;
                k=i;
            }
        }
        printf("%d %d\n",k,m);
    }
}






















  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值