51nod 最大M子段和 V1,V2,V3 dp 贪心 heap(bzoj2288)

最大M子段和:DP与贪心解法
博客探讨了如何从给定序列中选择最多M个不相交部分,以最大化总和。V1使用简单的动态规划,V2和V3采用贪心策略,处理连续正数和负数段,利用小根堆合并,保证最优解。当正数段数量大于等于M时,直接选取所有正数。

题意:给一个长度为n的序列,要求选出m个不相交的部分,要求总和最大,如果m>= n个数中正数的个数,那么输出所有正数的和。。
V1:n,m<=5000.
V2:n,m<=50000.
V3:n,m<=500000.

V1:
一个简单的DP。
明显有f[i][j]表示做到第i个,选择了j段。
那么可以推导:
新开一段f[i][j]=f[i1][j1]+a[i]
不选f[i][j]=f[i1][j]
承接前一段f[i][j]=max(f[i1][j]+a[i]),其实并不是这样做的,这样子写很明显是错的,想想为什么。

因为这样不能保证连续k个数相邻(假设第j段取了k个)。
那么我们就要换一种思想。
设f[i][j]表示前i个数字,选择了j段,不一定选j。
g[i][j]表示一定选j。
那么有:
g[i][j]=max(f[i1][j]+a[i],g[i1][j]+a[i])
f[i][j]=max(f[i1][j],g[i][j])
是我很久以前做的了,所以是pascal的,方法不是我上面的这个,是f_zyj的。

uses math;
var
    dp,pre,a:array[0..1000000]of int64;
    k,p,m,n,ans:int64;
    i,j:longint;
begin
    readln(n,m);
    dp[0]:=-maxlongint;
    for i:=1 to n do
    begin
        readln(a[i]);
        dp[i]:=-maxlongint;
    end;
    pre[0]:=0;
    ans:=maxlongint;
    for j:=1 to m do
    begin
        ans:=-maxlongint;;
        for i:=1 to n do
        begin
            if i=1 then dp[i]:=pre[i-1]+a[i]
            else 
            begin
                if dp[i-1]>pre[i-1] then
                dp[i]:=dp[i-1]+a[i]
                else dp[i]:=pre[i-1]+a[i];
            end;
            pre[i-1]:=ans;
            ans:=max(ans,dp[i]);
        end;
        pre[n]:=ans;
    end;
    writeln(pre[n]);
end.

V2,V3其实都是同一种方法,时间复杂度nlogn。
具体方法是贪心。
把所有连续正数,负数段处理出来,接下来的问题就是如何处理。
如果正数段<=m直接选,>m我们贪心做。
每次找到绝对值最小的一个,然后用小根堆和左右两个合并,可以证明最优:
设S(i)表示第i个数(绝对值最小)(合并以后)的绝对值。
1.如果i是负数,那么相邻两个是正数,权值减少S(i)。
2.如果i是正数,那么相邻两个是负数,权值仍然减少S(i).
一直处理直到正数<=m为止。
V2也是bzoj2288的原题。
V2:

#include<cstdio>
#include<algorithm>
#include<cstring>
#include<queue>
#define abs(x) (x>0?x:-x)
#define fo(i,a,b) for(int i=a;i<=b;i++)
#define fd(i,a,b) for(int i=a;i>=b;i--)
using namespace std;
const int N=1e6+5;
int n,m,l[N],r[N];
typedef long long ll;
ll a[N];
struct node
{
    int x;
    bool operator <(const node &y) const
    {
        return abs(a[x])>abs(a[y.x]);
    }
};
priority_queue<node>q;
int main()
{
    scanf("%d%d",&n,&m);
    ll y=0,ans=0;
    int tot=0;
    fo(i,1,n)
    {
        ll x;
        scanf("%lld",&x);
        if(!x)continue;
        if (!y)
        {
            y=x;
            continue;
        }
        if (x>0)
        {
            if (y>0)y+=x;
            else a[++tot]=y,y=x;
        }
        else
        {
            if (y<0)y+=x;
            else a[++tot]=y,y=x;
        }
    }
    a[++tot]=y;
    int cnt=0;
    fo(i,1,tot)
    {
        if (a[i]>0)++cnt,ans+=a[i];
        l[i]=i-1,r[i]=i+1;
        q.push((node){i});
    }
    l[0]=0;r[0]=1;
    l[tot+1]=tot,r[tot+1]=tot+1;
    int tmp,L,R;
    while (cnt>m)
    {
        int x=q.top().x;
        q.pop();
        if (l[r[x]]!=x||r[l[x]]!=x)continue;
        if (!a[x]||(a[x]<0&&(l[x]<1||r[x]>tot)))continue;
        ans-=abs(a[x]),--cnt;
        a[x]=a[x]+a[l[x]]+a[r[x]];
        L=l[l[x]],R=r[r[x]];
        l[x]=L,r[x]=R,r[L]=x,l[R]=x;
        q.push((node){x});
    }
    printf("%lld\n",ans);
}

至于V3,其实也差不多,只是把首尾相接然后一起做罢了。
稍微有点小细节修改一下就OK

#include<cstdio>
#include<algorithm>
#include<cstring>
#include<queue>
#define abs(x) (x>0?x:-x)
#define fo(i,a,b) for(int i=a;i<=b;i++)
#define fd(i,a,b) for(int i=a;i>=b;i--)
using namespace std;
const int N=1e6+5;
int n,m,l[N],r[N];
typedef long long ll;
ll a[N];
struct node
{
    int x;
    bool operator <(const node &y) const
    {
        return abs(a[x])>abs(a[y.x]);
    }
};
priority_queue<node>q;
int main()
{
    scanf("%d%d",&n,&m);
    ll y=0,ans=0;
    int tot=0;
    fo(i,1,n)
    {
        ll x;
        scanf("%lld",&x);
        if(!x)continue;
        if (!y)
        {
            y=x;
            continue;
        }
        if (x>0)
        {
            if (y>0)y+=x;
            else a[++tot]=y,y=x;
        }
        else
        {
            if (y<0)y+=x;
            else a[++tot]=y,y=x;
        }
    }
    a[++tot]=y;
    while (tot>1&&((a[tot]>0&&a[1]>0)||(a[tot]<0&&a[1]<0)))
    a[1]+=a[tot],tot--;
    int cnt=0;
    fo(i,1,tot)
    {
        if (a[i]>0)++cnt,ans+=a[i];
        l[i]=i-1,r[i]=i+1;
        q.push((node){i});
    }
    l[1]=tot;r[tot]=1;
    int tmp,L,R;
    while (cnt>m)
    {
        int x=q.top().x;
        q.pop();
        if (l[r[x]]!=x||r[l[x]]!=x)continue;
        if (!a[x]||(a[x]<0&&(l[x]<1||r[x]>tot)))continue;
        ans-=abs(a[x]),--cnt;
        a[x]=a[x]+a[l[x]]+a[r[x]];
        L=l[l[x]],R=r[r[x]];l[l[x]]=r[l[x]]=l[r[x]]=r[r[x]]=0;
        l[x]=L,r[x]=R,r[L]=x,l[R]=x;
        q.push((node){x});
    }
    printf("%lld\n",ans);
}
题目 51nod 3478 涉及一个矩阵问题,要求通过最少的操作次数,使得矩阵中至少有 `RowCount` 行 `ColumnCount` 列是回文的。解决这个问题的关键在于如何高效地枚举所有可能的行列组合,并计算每种组合所需的操作次数。 ### 解法思路 1. **预处理每一行每一列变为回文所需的最少操作次数**: - 对于每一行,计算将其变为回文所需的最少操作次数。这可以通过比较每对对称位置的值是否相同来完成。 - 对于每一列,计算将其变为回文所需的最少操作次数,方法同上。 2. **枚举所有可能的行列组合**: - 由于 `N` `M` 的最大值为 8,因此可以枚举所有可能的行组合列组合。 - 对于每一种组合,计算其所需的最少操作次数,并取最小值。 3. **计算操作次数**: - 对于每一种组合,需要计算哪些行列需要修改,并且注意行列的交叉点可能会重复计算,因此需要去重。 ### 代码实现 以下是一个可能的实现方式,使用了枚举位运算来处理组合问题: ```python def min_operations_to_palindrome(matrix, row_count, col_count): import itertools N = len(matrix) M = len(matrix[0]) # Precompute the cost to make each row a palindrome row_cost = [] for i in range(N): cost = 0 for j in range(M // 2): if matrix[i][j] != matrix[i][M - 1 - j]: cost += 1 row_cost.append(cost) # Precompute the cost to make each column a palindrome col_cost = [] for j in range(M): cost = 0 for i in range(N // 2): if matrix[i][j] != matrix[N - 1 - i][j]: cost += 1 col_cost.append(cost) min_total_cost = float(&#39;inf&#39;) # Enumerate all combinations of rows and columns rows = list(range(N)) cols = list(range(M)) from itertools import combinations for row_comb in combinations(rows, row_count): for col_comb in combinations(cols, col_count): # Calculate the cost for this combination cost = 0 # Add row costs for r in row_comb: cost += row_cost[r] # Add column costs for c in col_comb: cost += col_cost[c] # Subtract the overlapping cells for r in row_comb: for c in col_comb: # Check if this cell is part of the palindrome calculation if r < N // 2 and c < M // 2: if matrix[r][c] != matrix[r][M - 1 - c] and matrix[N - 1 - r][c] != matrix[N - 1 - r][M - 1 - c]: cost -= 1 min_total_cost = min(min_total_cost, cost) return min_total_cost # Example usage matrix = [ [0, 1, 0], [1, 0, 1], [0, 1, 0] ] row_count = 2 col_count = 2 result = min_operations_to_palindrome(matrix, row_count, col_count) print(result) ``` ### 代码说明 - **预处理成本**:首先计算每一行每一列变为回文所需的最少操作次数。 - **枚举组合**:使用 `itertools.combinations` 枚举所有可能的行列组合。 - **计算成本**:对于每一种组合,计算其成本,并考虑行列交叉点的重复计算问题。 ### 复杂度分析 - **时间复杂度**:由于 `N` `M` 的最大值为 8,因此枚举所有组合的时间复杂度为 $ O(N^{RowCount} \times M^{ColCount}) $,这在实际中是可接受的。 - **空间复杂度**:主要是存储预处理的成本,空间复杂度为 $ O(N + M) $。 ### 相关问题 1. 如何优化矩阵中行列的枚举组合以减少计算时间? 2. 在计算行列的交叉点时,如何更高效地处理重复计算的问题? 3. 如果矩阵的大小增加到更大的范围,如何调整算法以保持效率? 4. 如何处理矩阵中行列的回文条件不同时的情况? 5. 如何扩展算法以支持更多的操作类型,例如翻转某个区域的值?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值