zoukankan      html  css  js  c++  java
  • CF922D Robot Vacuum Cleaner

    题目分析

    观察数据范围 (n leq 10^5), 还有 "任意顺序连接" 及 "最大化" 的要求, 自然想到了做法 : 邻项交换

    考虑相邻的两个位置 (i)(j = i + 1), 他们的相对顺序不会影响 ([1, i - 1])([j + 1, n]) 这些位置的答案. 所以只需要考虑 (i, j) 之间的贡献.

    1. (i)(j) 之前, (i, j) 之间的贡献应为 : (countS ( Str(i) ) * countH ( Str(j) ))
    2. (j)(i) 之前, (i, j) 之间的贡献应为 : (countS ( Str(j) ) * countH ( Str(i) ))

    只需比较以上两式之间的大小就能确定 (i, j) 之间的相对顺序. 由于这满足严格弱序, 可以扩展到全局.

    把式子写成 (Cmp()) 就能用 (std::sort())(O(nlogn)) 求出最优的排列顺序.

    统计答案非常简单, (O(n)) 扫一遍即可.

    细节请看代码.

    代码实现

    #include <cstdio>
    #include <string>
    #include <iostream>
    #include <algorithm>
    
    const int N = 1e5;
    
    int n;
    std::string Str[N + 5];
    
    struct Node { int S1, S2, Id; } Q[N + 5];
    
    bool Cmp (Node, Node);
    
    int main() {
    	std::ios::sync_with_stdio (false);
    
    	std::cin >> n;
    	for (int i = 1; i <= n; ++i) {
    		std::cin >> Str[i];
    		int Len = Str[i].length();
    		for (int j = 0; j < Len; ++j)
    			Q[i].S1 += (Str[i][j] == 's'), Q[i].S2 += (Str[i][j] == 'h');
    		Q[i].Id = i;
    	
    	} std::sort (Q + 1, Q + 1 + n, Cmp);
    	
    	auto NowS = 0ll, Ans = 0ll;
    	for (int i = 1; i <= n; ++i) {
    		int Len = Str[Q[i].Id].length();
    		for (int j = 0; j < Len; ++j) {
    			char tap = Str[Q[i].Id][j];
    			if (tap == 's') ++NowS;
    			else Ans += NowS;
    		}
    	} printf ("%lld
    ", Ans);
    	return 0;
    
    } bool Cmp (Node X, Node Y) {
    	return 1LL * X.S1 * Y.S2 > 1LL * Y.S1 * X.S2;
    }
    
  • 相关阅读:
    Eclipse中支持js提示
    数据库命名规则
    JavaWeb 命名规则
    Ajax&json
    js中,var 修饰变量名和不修饰的区别
    javaScript知识点
    Bootstrap 栅格系统
    文本框如果不输入任何内容提交过后是一个空字符串还是null
    根据汇总数量依次扣减的SQL新语法
    asp.net中使用forms验证
  • 原文地址:https://www.cnblogs.com/Rothen/p/14072718.html
Copyright © 2011-2022 走看看