• [luoguP3668] [USACO17OPEN]Modern Art 2 现代艺术2(栈)


    传送门

    还是一个字——栈

    然后加一大堆特判

    至少我是这么做的

    我的代码

    #include <cstdio>
    #include <iostream>
    #define N 100001
    #define max(x, y) ((x) > (y) ? (x) : (y))
    
    int s[N], a[N], b[N];
    int n, top, ans;
    
    inline int read()
    {
    	int x = 0, f = 1;
    	char ch = getchar();
    	for(; !isdigit(ch); ch = getchar()) if(ch == '-') f = -1;
    	for(; isdigit(ch); ch = getchar()) x = (x << 1) + (x << 3) + ch - '0';
    	return x * f;
    }
    
    int main()
    {
    	int i, x;
    	n = read();
    	for(i = 1; i <= n; i++)
    	{
    		a[i] = read();
    		b[a[i]]++;
    	}
    	for(i = 1; i <= n; i++)
    	{
    		if(!top && !a[i]) continue;
    		else if(!a[i])
    		{
    			s[++top] = a[i];
    			continue;
    		}
    		if(s[top] == a[i] && b[a[i]] > 1)
    		{
    			ans = max(ans, top);
    			b[a[i]]--;
    		}
    		else if(s[top] == a[i] && b[a[i]] == 1)
    		{
    			ans = max(ans, top);
    			b[a[i]]--;
    			top--;
    		}
    		else if(b[a[i]] == 1) ans = max(ans, top + 1);
    		else
    		{
    			s[++top] = a[i];
    			b[a[i]]--;
    		}
    	}
    	if(top) puts("-1");
    	else printf("%d
    ", ans);
    	return 0;
    }
    

      

    看了题解

    发现预处理出来每种颜色最左边和最右边的位置会更好处理

    如果两种颜色有交集,直接输出-1

    题解代码

    #include<bits/stdc++.h>
    using namespace std;
    typedef long long LL;
    int n;
    int a[100008],l[100008],r[100008];
    int s[100008],top;
    int tmp,ans;
    int main()
    {
        cin>>n;
        for(int i=1;i<=n;i++){
            cin>>a[i];
            if(!l[a[i]])    l[a[i]]=i;
            r[a[i]]=i;
        }
        for(int i=1;i<=n;i++){
            if(a[i]==0){
                if(top){
                    cout<<-1;
                    return 0;
                }
                else continue;
            }
            if(l[a[i]]==i){
                if(top&&r[a[i]]>r[s[top]]){
                    cout<<-1;
                    return 0;
                }
                s[++top]=a[i];
                tmp++;
                ans=max(ans,tmp);
            }
            if(r[a[i]]==i){
                top--;
                tmp--;
            }
        }
        cout<<ans;
        return 0;    
    }
    

      

    5

    1 2 1 2 1

    这组数据,我输出-1,题解输出2

    好像题解错了,但因为数据水,所以,你懂的

  • 相关阅读:
    H3C-U200无法通过公网访问内网服务器
    mtr工具
    nginx网页跳转失败-302
    http协议
    接口 Swagger 部分Web API的隐藏
    接口 ApiController调用Controller 模拟Session 封装
    接口 Swagger 03 基于Token的身份认证
    电商 批量修改图片分辨率
    接口 Swagger 01 让Asp.net MVC项目显示API文档
    接口 Swagger 02 显示代码注释
  • 原文地址:https://www.cnblogs.com/zhenghaotian/p/7505368.html
Copyright © 2020-2023  润新知