首页 > 代码库 > 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 贪心
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。