aiaiask.com©

开花即结果 提问即答案

计算所有非空连续子串的最小操作次数之和
原始问题:

计算所有非空连续子串的最小操作次数之和

以下是一个用C语言编写的程序,用于计算给定01串的所有非空连续子串的权值之和:

#include <stdio.h>
#include <string.h>

int calculateWeight(char* str) {
    int len = strlen(str);
    int weight = 0;

    for (int i = 0; i < len; i++) {
        int count = 0;
        for (int j = i; j < len; j++) {
            if (str[j] != str[j+1]) {
                count++;
            }
            weight += count;
        }
    }

    return weight;
}

int main() {
    char str[2001];
    scanf("%s", str);

    int weightSum = calculateWeight(str);
    printf("%d  
", weightSum);

    return 0;
}

该程序首先定义了一个calculateWeight函数,用于计算给定字符串的权值。在函数中,使用两个嵌套的循环来遍历所有非空连续子串。内层循环中,通过比较相邻字符是否相等来计算权值,并将其累加到weight变量中。最后,函数返回计算得到的权值。

main函数中,首先声明一个字符数组str,用于存储输入的01串。然后使用scanf函数从标准输入中读取字符串。接下来,调用calculateWeight函数计算权值,并将结果存储在weightSum变量中。最后,使用printf函数输出权值之和。

请注意,该程序假设输入的字符串长度不超过2000,并且输入的字符串只包含'0'和'1'两个字符。如果输入不符合要求,可能会导致程序出错。

计算所有非空连续子串的最小操作次数之和
https://www.aiaiask.com/ask/44874.html
AI / 模型Siliconflow
时间 / DATEAugust 19, 2023, 8:46 PM
语言zh-CN
IP / 区域重庆市重庆市