跳到正文

题解

题解:P16857 [GKS 2021 #F] Trash Bins

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

文章信息

发布
2026年6月11日
收录
2026年8月25日
更新
2026年8月26日
篇幅
约 5 分钟
题目
P16857

版本

  1. v1当前

P16857 [GKS 2021 #F] Trash Bins

题目链接: https://www.acmicpc.net/problem/16857

题目大意

给定由字符 0 和 1 构成的字符串,其中 1 代表垃圾桶,0 代表普通位置。对每一个位置,计算它到最近垃圾桶的距离,最终求出所有位置的距离总和。本题包含多组测试数据,按指定格式输出每组答案。

解题思路

采用两次线性递推结合字符串处理求解,分为左递推、右递推两个步骤:

左递推:从左向右遍历字符串,维护左侧最近垃圾桶的位置 pos。若当前位置是垃圾桶,则距离为 0;否则当前位置到左侧垃圾桶的距离为 j−pos。

右递推:从右向左遍历字符串,维护右侧最近垃圾桶的位置 pos。用当前已存距离与 pos−j 取最小值,得到该位置到垃圾桶的最短距离。

最后遍历所有位置,累加最短距离得到答案。 全程仅三次线性遍历,算法效率高。 复杂度分析

时间复杂度:O(∑n),n 为单组字符串长度,整体为线性复杂度。 空间复杂度:O(n),使用数组存储每个位置的最短距离。

代码实现

C++
#include<bits/stdc++.h>
using namespace std;

int a[110];
string s[110];
int d[500010];

int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    int t;
    cin >> t;
    // 读入多组数据
    for(int i = 1; i <= t; ++i){
        cin >> a[i] >> s[i];
    }
    // 依次处理每组测试用例
    for(int i = 1; i <= t; ++i){
        cout << "Case #" << i << ": ";
        int n = a[i];
        string str = s[i];
        long long sum = 0;
        
        // 左递推:计算到左侧最近垃圾桶的距离
        int pos = -1e9;
        for(int j = 0; j < n; ++j){
            if(str[j] == '1'){
                pos = j;
                d[j] = 0;
            }else{
                d[j] = j - pos;
            }
        }
        
        // 右递推:计算到右侧最近垃圾桶的距离,并取最小值
        pos = 1e9;
        for(int j = n - 1; j >= 0; --j){
            if(str[j] == '1'){
                pos = j;
            }else{
                d[j] = min(d[j], pos - j);
            }
        }
        
        // 累加所有位置的最短距离
        for(int j = 0; j < n; ++j){
            sum += d[j];
        }
        cout << sum << '\n';
    }
    return 0;
}

易错点说明

距离总和可能较大,必须使用 long long 存储总和,避免整数溢出。 初始化垃圾桶位置时,使用极大 / 极小值 ±109,保证边界位置可以正常计算距离。 字符串下标从 0 开始,遍历区间不要出错。

额外优化建议(可选,提升题解质量) 代码精简优化 数组 a、s 可以不用批量存储,边读边算,进一步节省空间,修改后核心代码:

C++
int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    int t;
    cin >> t;
    for(int i = 1; i <= t; ++i){
        cout << "Case #" << i << ": ";
        int n;
        string str;
        cin >> n >> str;
        long long sum = 0;
        int pos = -1e9;
        for(int j = 0; j < n; j++){
            if(str[j] == '1') pos = j, d[j] = 0;
            else d[j] = j - pos;
        }
        pos = 1e9;
        for(int j = n-1; j >= 0; j--){
            if(str[j] == '1') pos = j;
            else d[j] = min(d[j], pos - j);
        }
        for(int j = 0; j < n; j++) sum += d[j];
        cout << sum << '\n';
    }
    return 0;
}
原文