zoukankan      html  css  js  c++  java
  • 【贪心+一点小思路】Zoj

    借用别人一句话,还以为是个高贵的dp... ...

    一打眼一看是波兰式的题,有点懵还以为要用后缀表达式或者dp以下什么什么的,比赛后半阶段才开始仔细研究这题发现贪心就能搞,奈何读错题了!!交换的时候可以任意两个字符交换然而就那么看成了只能相邻的数字字符与'*'字符交换....../(ㄒoㄒ)/~~...但赛后补题的时候发现细节考虑的不好,还是应该锻炼下自己的逻辑整理...

    怎么贪咧...

    第一步,全数字串即合法,直接输出0即可;

    第二步,数字不够的话要添。所谓数字够,即数字的个数至少要比星号个数多1,否则可以把缺少的数字(al+1-di)加在最开头,这样是最直接理想的。相应的,这也相当于增添操作的次数进行了(al+1-di)次;

    第三步,在数字个数与星号个数都合法的条件下,不合法星号的位置要进行交换,交换策略是和该星号后的一个数字交换;这样的话就能保证每一个星号前是合法的,可能会有人对这一步不太理解:

    1 for(int i = 0; i < len; i++)
    2 {
    3     if(str[i] == '*') ta++;
    4     else td++;
    5     if(td-ta<1)
    6     {
    7         td++; ta--; ans++;
    8     }
    9 }

    因为所有数字个数与字符个数都已经是合法的了,所以大可以不必考虑交换的具体位置,保证星号前合法的交换总会合法的。

    附代码:

     1 #include<iostream>
     2 #include<cstdio>
     3 #include<cstdlib>
     4 #include<cstring>
     5 #include<string>
     6 using namespace std;
     7 int main()
     8 {
     9     int T; cin >> T;
    10     while(T--)
    11     {
    12         string str;
    13         cin >> str;
    14         int len = str.length();
    15 
    16         int al, di; al = di = 0; //初始串的数字个数与星号个数
    17         for(int i = 0; i < len; i++) if(str[i] == '*') al++;
    18         if(al == 0) {printf("0
    "); continue;}
    19         di = len-al;
    20         int need; //是否缺少数字字符
    21         if(di - al >= 1) need = 0; else need = al+1-di;
    22 
    23         int td, ta; td = need; ta = 0;
    24         int ans = need;
    25         for(int i = 0; i < len; i++)
    26         {
    27             if(str[i] == '*') ta++;
    28             else td++;
    29             if(td-ta<1)
    30             {
    31                 td++; ta--; ans++;
    32             }
    33         }
    34         cout << ans << endl;
    35     }
    36     return 0;
    37 }
    View Code
  • 相关阅读:
    安装SQLserver2008时出现的错误
    第二章 语法陷阱
    分享:APK高级保护方法解析(三)
    设计模式_命令模式
    POJ-3134-Power Calculus(迭代加深DFS)
    Rational Rose2007具体安装步骤
    webAPP开发的问题(总结)
    基于Linux的智能家居的设计(5)
    获取表数据的插入SQL
    POJ 3667 Hotel(线段树)
  • 原文地址:https://www.cnblogs.com/LLGemini/p/4715441.html
Copyright © 2011-2022 走看看