uva live 7637 Balanced String (贪心)

超、凢脫俗 2022-01-05 15:25 284阅读 0赞

题目链接:https://icpcarchive.ecs.baylor.edu/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=5659

题意:

  你有一个只包含”(“ 和 “)” 的串,每一个位置有个数值,这个数值是当前的左括号-右括号的值。

  例:()() 数值就是1010。

  给你一个打乱了的数值,要你构造出字典序最小的字符串。

题解:

  因为左括号比右括号小,所以我们要尽量的选择左括号,选择左括号会使得数值增大,如果这个数值不能继续增大了我们就只能选择右括号。

  记得要初始化

ContractedBlock.gif ExpandedBlockStart.gif

  1. 1 #include <iostream>
  2. 2 #include <cstdio>
  3. 3 #include <cstring>
  4. 4 #include <string>
  5. 5 #include <algorithm>
  6. 6 #include <cmath>
  7. 7 #include <vector>
  8. 8 #include <queue>
  9. 9 #include <map>
  10. 10 #include <stack>
  11. 11 #include <set>
  12. 12 using namespace std;
  13. 13 typedef long long LL;
  14. 14 typedef unsigned long long uLL;
  15. 15 #define ms(a, b) memset(a, b, sizeof(a))
  16. 16 #define pb push_back
  17. 17 #define mp make_pair
  18. 18 #define eps 0.0000000001
  19. 19 #define IOS ios::sync_with_stdio(0);cin.tie(0);
  20. 20 const LL INF = 0x3f3f3f3f3f3f3f3f;
  21. 21 const int inf = 0x3f3f3f3f;
  22. 22 const int mod = 1e9+7;
  23. 23 const int maxn = 100000+10;
  24. 24 int a[maxn];
  25. 25 int num[maxn];
  26. 26 int last[maxn];
  27. 27 int ans[maxn];
  28. 28 void solve()
  29. 29 {
  30. 30 ms(num, 0);
  31. 31 ms(last, 0);
  32. 32 int n;scanf("%d", &n);
  33. 33 for(int i = 0;i<n;i++) scanf("%d", &a[i]);
  34. 34 for(int i = 0;i<n;i++){
  35. 35 if(a[i]<0){
  36. 36 printf("invalid");return;
  37. 37 }
  38. 38 }
  39. 39 for(int i = 0;i<n;i++){
  40. 40 num[a[i]]++;
  41. 41 }
  42. 42 last[0]=0;
  43. 43 for(int i=1;i<=n;i++){
  44. 44 if(num[last[i-1]+1]){
  45. 45 last[i] = last[i-1]+1;
  46. 46 ans[i] = 1;
  47. 47 num[last[i-1]+1]--;
  48. 48 }
  49. 49 else if(num[last[i-1]-1]){
  50. 50 last[i] = last[i-1]-1;
  51. 51 ans[i] = 0;
  52. 52 num[last[i-1]-1]--;
  53. 53 }
  54. 54 else{
  55. 55 printf("invalid");return;
  56. 56 }
  57. 57 }
  58. 58 if(ans[n]==0){
  59. 59 for(int i = 1;i<=n;i++)
  60. 60 if(ans[i]==1) printf("(");
  61. 61 else printf(")");
  62. 62 }else{
  63. 63 printf("invalid");return;
  64. 64 }
  65. 65 }
  66. 66 int main() {
  67. 67 #ifdef LOCAL
  68. 68 freopen("input.txt", "r", stdin);
  69. 69 // freopen("output.txt", "w", stdout);
  70. 70 #endif
  71. 71 // IOS
  72. 72 int t;scanf("%d", &t);
  73. 73 int cnt = 1;
  74. 74 while(t--){
  75. 75 printf("Case %d: ", cnt++);
  76. 76 solve();
  77. 77 printf("\n");
  78. 78 }
  79. 79 return 0;
  80. 80 }

转载于:https://www.cnblogs.com/denghaiquan/p/7288100.html

发表评论

表情:
评论列表 (有 0 条评论,284人围观)

还没有评论,来说两句吧...

相关阅读

    相关 uva 10716——Evil Straw Warts Live

    题意:给定一个字符串,然后判断最小经过若干次交换然后使这个串变成一个回文串(每次可以交换相邻两位)。 思路:贪心。如果一个串的奇数字母的个数为奇数个,那么一定是不可

    相关 [UVA1437] String painter

    [题目链接][Link 1] 题意   有两个由小写英文字母组成的等长字符串A和B。你可以一次性将一个字符串的一个子串中的字符全部刷成任何你想要同一字符。求把字符串A刷成B