跳到正文

题解

P5751 [NOI1999] 01串 题解

catec_kelvin_catec约 5 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 5 分钟
题目
P5751

版本

  1. v1当前

😎 01串大冒险

P5751 [NOI1999] 01串

本菜鸟第一篇题解 求管理员通过
个人中心

题目描述

给定7个整数,要你设计一个长度为nn的0101串,满足:

  1. 每个字符是00或11
  2. 任意长度为l0l0的连续子串中,00的个数在[a0,b0][a0, b0]之间
  3. 任意长度为l1l1的连续子串中,11的个数在[a1,b1][a1, b1]之间

找出满足条件的0101串中1的个数最多的那个。

解题思路

🤔 问题分析

这题是个差分约束系统问题,需要用SPFA算法解决。

🧠 核心思路

定义前缀和数组pre[i]pre[i]表示前ii个字符中11的个数:

  • 每个字符是00或11:0≤pre[i]−pre[i−1]≤10 ≤ pre[i] - pre[i-1] ≤ 1
  • l0l0子串约束:a0≤(l0−(pre[j+l0−1]−pre[j−1]))≤b0a0 ≤ (l0 - (pre[j+l0-1] - pre[j-1])) ≤ b0
  • l1l1子串约束:a1≤(pre[j+l1−1]−pre[j−1])≤b1a1 ≤ (pre[j+l1-1] - pre[j-1]) ≤ b1

把这些不等式转化为图的边,用SPFASPFA求最短路径。

✨ 代码实现

C++
#include<iostream>
#include<queue>
using namespace std;

int n, cnt, a0, a1, b0, b1, l0, l1;
int head[1005], dist[1005], inCount[1005];
bool inQueue[1005];

class Edge {
public:
    int to, next, weight;
} edges[4005];

queue<int> q;

inline void addEdge(int from, int to, int weight) {
    edges[++cnt] = {to, head[from], weight};
    head[from] = cnt;
}

int main() {
    int i;
    cin >> n >> a0 >> b0 >> l0 >> a1 >> b1 >> l1;

    // 基本约束:每个位置是0或1
    for(i = 1; i <= n; i++) {
        addEdge(i, i-1, 0);      // pre[i-1] - pre[i] ≤ 0
        addEdge(i-1, i, 1);      // pre[i] - pre[i-1] ≤ 1
    }

    // l0子串约束
    for(i = l0; i <= n; i++) {
        addEdge(i, i-l0, b0-l0);    // 0的个数 ≤ b0
        addEdge(i-l0, i, l0-a0);    // 0的个数 ≥ a0
    }

    // l1子串约束
    for(int i = l1; i <= n; i++) {
        addEdge(i, i-l1, -a1);      // 1的个数 ≥ a1
        addEdge(i-l1, i, b1);        // 1的个数 ≤ b1
    }

    // SPFA初始化
    q.push(0);
    inQueue[0] = true;
    for(i = 1; i <= n; ++i) {
        dist[i] = 0x7fffffff;
    }

    // SPFA算法
    while(!q.empty()) {
        #define to edges[i].to
        int u = q.front();
        q.pop();
        inQueue[u] = false;

        for(i = head[u]; i; i = edges[i].next) {
            if(dist[u] + edges[i].weight < dist[to]) {
                dist[to] = dist[u] + edges[i].weight;
                if(++inCount[to] == n) {
                    cout << -1;
                    return 0;
                }
                if(!inQueue[to]) {
                    inQueue[to] = true;
                    q.push(to);
                }
            }
        }
    }

    cout << dist[n];
    return 0;
}

🎯 代码说明

  • 图构建:所有约束条件转化为图的边
  • SPFA算法:处理可能有负权边的最短路径
  • 负环检测:入队次数超过nn次说明无解
  • 结果输出:dist[n]dist[n]就是11的最大个数

💡 复杂度分析

  • 时间复杂度:O(kE)O(kE),kk是常数,EE是边数
  • 空间复杂度:O(n+E)O(n + E)

🎉 总结

字符串问题变身图论问题,用SPFASPFA算法巧妙解决差分约束系统,找到最多11的0101串!

原文