牛客多校第八场

https://ac.nowcoder.com/acm/contest/888#question

B

签到题,代码可真短。

题意:给n个数,对于每个连续子序列求区间内不同数字的个数的和。

 做法:一开始枚举每个区间的右端点i,判断每个数字在区间左端点为1~i这个范围内对右端点i的贡献,然后累加答案,然后超时了。

之后想到,每次变化范围只会变一个数字,只会改变一个数字的贡献,所以开了一个sum记录所有数字的贡献就好了。

#include<bits/stdc++.h>
using namespace std;

const int maxn=1e5+10;
#define ll long long
int maxx[maxn];
int main()
{
    int n;
    scanf("%d",&n);
    ll ans=0;
    ll sum=0;
    int t;
    for(int i=1; i<=n; i++)
    {
        scanf("%d",&t);
        sum=sum-maxx[t]+i;
        maxx[t]=i;
        ans=ans+sum;
    }
    printf("%lld",ans);
}
View Code

签到题

#include<bits/stdc++.h>
using namespace std;

const int maxn=1e5+10;
char s[maxn];
int main()
{
    scanf("%s",s+1);
    int len=strlen(s+1);
    int ans=0;
    stack<char> st;
    for(int i=1; i<=len; i++)
    {
        st.push(s[i]);
        if(st.size()>=3)
        {
            char c1=st.top();st.pop();
            char c2=st.top();st.pop();
            char c3=st.top();st.pop();
            if(c1==c2&&c2==c3)
                ans++;
            else
            {
                st.push(c3);st.push(c2);st.push(c1);
            }
        }
    }
    printf("%d",ans);



}
View Code

猜你喜欢

转载自www.cnblogs.com/dongdong25800/p/11333861.html