• noip模拟赛 写代码


    分析:这其实就是括号匹配题,一眼贪心题,不过一开始贪错了,以为([)]是合法的......其实括号之间不能嵌套.

          一开始的想法是尽量往左边填左括号,因为每种括号的数量都确定了,那么左括号和右括号的数量也就确定了,但是这样会有一个问题:1 1 1 2 3 1 1 3 2 1,最后两个1被指定为右括号,这样的贪心会使它嵌套.正着贪心似乎很难,沿用之前模拟赛的思路,倒着贪心:从已知推向未知.

          题目中告诉了右括号的位置,从后往前枚举,为了尽可能地防止嵌套,在右边如果能放左括号就尽量放左括号,不行就放右括号,最后判断一下能不能合法就可以了.

    #include <cstdio>
    #include <cstring>
    #include <iostream>
    #include <algorithm>
    
    using namespace std;
    
    int n, m, a[1000010], cnt[1000010], pos[1000010],p[1000010], ans[1000010], tot[1000010];
    
    int main()
    {
        scanf("%d", &n);
        for (int i = 1; i <= n; i++)
        {
            scanf("%d", &a[i]);
            cnt[a[i]]++; 
        }
        for (int i = 1; i <= n; i++)
            if (cnt[i] % 2 != 0)
            {
                printf("NO
    ");
                return 0;
            }
        scanf("%d", &m);
        for (int i = 1; i <= m; i++)
        {
            int t;
            scanf("%d", &t);
            pos[t] = 1;
        }
        for (int i = n; i >= 1; i--)
        {
            if (pos[i] == 1)
            {
                tot[a[i]]++;
                ans[i] = 2;
                p[a[i]]--;
            }
            else
            {
                if (tot[a[i]] >= 1)
                {
                    tot[a[i]]--;
                    ans[i] = 1;
                    p[a[i]]++;
                }
                else
                {
                    tot[a[i]]++;
                    ans[i] = 2;
                    p[a[i]]--;
                }
            }
        }
        for (int i = 1; i <= n; i++)
            if (p[i] != 0)
            {
                printf("NO
    ");
                return 0;
            }
        for (int i = 1; i <= n; i++)
        {
            if (ans[i] == 1)
                printf("+%d ", a[i]);
            else
                printf("-%d ", a[i]);
        }
    
        return 0;
    }
  • 相关阅读:
    秋招结束了
    面向萌新的日麻面麻规则简化/改进
    DataTable 转换为Tree 树状结构
    jmeter beanshell断言
    jmeter请求参数包含中文
    Centos7 yum缓存rpm安装包
    nginx针对某个url限制ip访问,常用于后台访问限制
    有关json-lib2.4在转java对象时超过7位数的Double类型会出现科学计数法和精度丢失的问题
    SAP 下载安装
    android okhttp + retrofit使用
  • 原文地址:https://www.cnblogs.com/zbtrs/p/7780507.html
Copyright © 2020-2023  润新知