【dp/贪心】CF 780 (Div. 3), problem: (C) Get an Even String

Problem - C - Codeforces

难度: 1300

 

input
6
aabbdabdccc
zyx
aaababbb
aabbcc
oaoaaaoo
bmefbmuyw
output
3
3
2
0
2
7

开始没调出来, 去看DE了, 就不该往后看, 但是当时思维没跳出来, 也不一定做出来, 呜呜
当时是想着每次更新需要看前一次什么时候有这个字母

此题重要一点更新就是, 越靠前进行配对的字母才是最优, 把问题转化一下, n-配对的字母数即为结果,
这里贴两个代码, 第一个是小小不像dp的dp; 第二个是小小思维,这样做题感觉就简单了


代码一
#include <iostream>
#include <bits/stdc++.h>

using namespace std;
typedef long long LL;
const int N = 2e5+10;

int f[N];
char s[N];

int main()
{
    int t;
    // scanf("%d", &t);
    cin >> t;
    while(t --)
    {
        scanf("%s", s+1);//这种方法为了后面方便, 建议字符串从1开始
        int cnt = 0;
        int n=0;
        
        map<char,int> mp, l;
        
        f[0]=0;
        for(int i = 1; s[i];i++)
        {
            f[i]=f[i-1]+1;
            if(l[s[i]] && i>=l[s[i]])
                if(f[i]>f[l[s[i]]-1]+i-l[s[i]]-1)    
                {
                    f[i] = f[l[s[i]]-1]+i-l[s[i]]-1;
                    l.clear();
                }    
            
            l[s[i]]=i;
            n=i;
        }
        cout << f[n]<<'\n';
    }
    return 0;
    
}

代码二

#include <iostream>
#include <bits/stdc++.h>

using namespace std;
typedef long long LL;
const int N = 2e5+10;
int    be[30];
int f[N];
int main()
{
    int t;
    // scanf("%d", &t);
    cin >> t;
    string s;
    while(t --)
    {
        cin >> s;
        int cnt = 0;
        int n = s.size();
        
        map<char,int> mp;
        for(int i = 0; i<n;i++)
        {
            mp[s[i]]++;
            if(mp[s[i]]==2)    cnt ++, mp.clear();
        }
        cout << n-cnt*2<<'\n';
    }
    return 0;
    
}

 




posted @ 2022-04-02 18:57  la-la-wanf  阅读(82)  评论(0编辑  收藏  举报