首页 > 代码库 > Gym 100703K Word order 贪心

Gym 100703K Word order 贪心

题目链接

题目大意:给定一个长度为n的字符串,字符串仅由"F","N","A"三种字符组成,现有一种操作P,即把两个相邻的字符调换位置。要求把所有的A都放在所有的F左侧,问需要的最少操作P的次数。

思路:首先从左至右的扫描原串,对于每一个"A",设它的左侧有x个"F",则必然至少需要x次操作将"A"换到"F"的左侧或者把“F”换到"A"的右侧。然后对于每个"N",设它左侧有L_F个"F",右侧有R_A个"A",若L_F大于R_A,则更优解就是把"A"换到左侧,而反之,则是把"F"换到右侧。

#include <iostream>#include <cstdio>#include <cstring>#include <cmath>#include <algorithm>#include <set>using namespace std;#define MAXN 110char str[MAXN];int n;int main() {    scanf("%d", &n);    int ans = 0;    scanf("%s", str + 1);    int F_num = 0;    for(int i = 1; i <= n; i++) {        if(str[i] == F) F_num++;        else if(str[i] == A) ans += F_num;    }    for(int i = 1; i <= n; i++) {        if(str[i] != N) continue;        int st = i, ed = i;        while(str[ed] != N) ed++;        int len = ed - st + 1;        int L_F = 0, R_A = 0;        for(int j = 1; j < st; j++)            if(str[j] == F) L_F++;        for(int j = ed + 1; j <= n; j++)            if(str[j] == A) R_A++;        ans += len * min(L_F, R_A);    }    printf("%d\n", ans);    return 0;}

 

Gym 100703K Word order 贪心