数组打标记思想

今天是本蒟蒻去附中培训第二天

教练说了一种很重要的思想:标记思想

简单来说就是先初始化数组,然后根据题意来将数组进行标记

我们可以通过两道简单的题目来体会一下

1.NOIP2006 明明的随机数

简单来说这道题就是去重然后排序输出

代码如下

#include<bits/stdc++.h>
using namespace std;
int main()
{
  int n,m,a[10086];
  scanf("%d" , &n);
  for(int i = 0; i < n ;++ i)
    scanf("%d" ,&a[i]);
  sort( a, a+n);//快排
  m=n;
  for(int i = 0; i < n ;++ i)//此循环为打标记与去重
  {
    if(a[i]==a[i+1])//如果有重复
    {
      a[i] = 1;//则将重复的打上标记
      m --;//因为有重复,所以要在原来的基础上减1
    }
  }
  printf("%d\n" ,m);
  for(int i = 0 ; i < n;++ i)
  {
    if(a[i] != 1)
      printf("%d " ,a[i]);//将没有打上标记的输出
  }
  return 0;
}

2.NOIP2005 校门外的树

这道题体现的打标记思想就非常明显

代码如下

#include<bits/stdc++.h>
using namespace std;
int main()
{
  int l,m,a[10000+10],f,n,num=0;
  memset(a ,0 ,sizeof(a));//初始化数组所有元素的值为0
  scanf("%d%d",&l ,&m );
  for(int i = 0; i < m ;++ i)
  {
    scanf("%d%d", &f, &n);//f ,n 为砍掉的树的区间
    for(int j = f;j <= n;++ j)
      a[j] = 1;//将这个区间内的树打上标记
  }
  for(int i = 0 ; i <= l;++ i)
  {
    if(a[i] == 0)
      num ++;//如果有某棵树没被标记计数器就加一
  }
  printf("%d", num);//输出
  return 0;
}

所以我们可以看到,打标记思想是比较常用的

祝大家早日成为神犇

猜你喜欢

转载自www.cnblogs.com/nr386-blog/p/9320949.html
今日推荐