zoukankan      html  css  js  c++  java
  • cf 620C Pearls in a Row(贪心)

    d.有一串数字,要把这些数字分成若干连续的段,每段必须至少包含2个相同的数字,怎么分才能分的段数最多?

    比如 是1 2 1 3 1 2 1

    那么 答案是

    2
    1 3
    4 7

    即最多分在2段,第一段是1~3,第二段是4~7。

    即分成这2段:1 2 1,3 1 2 1

    s.很不错的一道贪心的题。当时没怎么细想,后来看了tourist的代码后得知。

    可以证明,满足贪心选择性质和最优子结构性质。

    贪心策略是:从前向后遍历,每次选择最小长度的符合条件的段。

    c.

    #include<iostream>
    #include<stdio.h>
    #include<set>
    using namespace std;
    
    #define MAXN 312345
    
    int a[MAXN];
    
    int _start[MAXN];
    int _end[MAXN];
    
    int main(){
    
        int n;
        set<int> existed;
        int cnt;
        int start;
    
        while(~scanf("%d",&n)){
            existed.clear();
    
            for(int i=0;i<n;++i){
                scanf("%d",&a[i]);
            }
    
            cnt=0;
            start=0;
            for(int i=0;i<n;++i){
                if(existed.find(a[i])!=existed.end()){
                    _start[cnt]=start;
                    _end[cnt]=i;
                    ++cnt;
    
                    existed.clear();
                    start=i+1;
                }
                else{
                    existed.insert(a[i]);
                }
            }
    
            if(cnt==0){
                printf("-1
    ");
            }
            else{
                _end[cnt-1]=n-1;
                printf("%d
    ",cnt);
                for(int i=0;i<cnt;++i){
                    printf("%d %d
    ",_start[i]+1,_end[i]+1);
                }
            }
        }
    
        return 0;
    }
    View Code
  • 相关阅读:
    LeetCode Power of Three
    LeetCode Nim Game
    LeetCode,ugly number
    LeetCode Binary Tree Paths
    LeetCode Word Pattern
    LeetCode Bulls and Cows
    LeeCode Odd Even Linked List
    LeetCode twoSum
    549. Binary Tree Longest Consecutive Sequence II
    113. Path Sum II
  • 原文地址:https://www.cnblogs.com/gongpixin/p/5152441.html
Copyright © 2011-2022 走看看