Luogu: P1496 burns Chibi (linear complexity optimization/discretization, popularization-, sorting)

topic:

Insert picture description here

analysis:

1. At first glance, I just did a question in the morning, the number of numbers involved in the pre+, post- statistical interval.

I wanted to use this idea and look at the data.

After thinking about it, if you don't need to deal with each number separately, then just subtract the beginning from the end!

2. Secondly, I got a wrong understanding. The numbers in the interval are only counted once. map!

#include<bits/stdc++.h>
using namespace std;
map<int,int> mm;
int main()
{
    
    
 int m;
 cin>>m;
 long long ans=0;
 for(int i=0;i<m;i++)
 {
    
    
  int a,b;
  cin>>a>>b;
  for(int i=a;i<b;i++) 
  {
    
    
   if(mm[i]==1) continue;
   mm[i]=1;
   ans++;
  }
 }
 cout<<ans;
}

Insert picture description here

Try set.

#include<bits/stdc++.h>
using namespace std;
set<int> s;
int main()
{
    
    
 int m;
 cin>>m;
 long long ans=0;
 for(int i=0;i<m;i++)
 {
    
    
  int a,b;
  cin>>a>>b;
  for(int i=a;i<b;i++) 
  {
    
    
   s.insert(i);
  }
 }
 cout<<s.size();
}

Insert picture description here

Take a look at the answer, to sort.

Well, then I figured it out by myself:

#include<bits/stdc++.h>
using namespace std;
struct node{
    
    
 int x1,x2;
} nn[20005];
bool cmp(node n1,node n2)
{
    
    
 return n1.x1<n2.x1;
}
int main()
{
    
    
 int m;
 cin>>m;
 long long ans=0;
 for(int i=0;i<m;i++)
 {
    
    
  cin>>nn[i].x1>>nn[i].x2;
 }
 sort(nn,nn+m,cmp);
 int last=nn[0].x1;
 for(int i=0;i<m;i++)
 {
    
    
  last=max(nn[i].x1,last);
  if(nn[i].x2<=last) continue;
  ans+=nn[i].x2-last;
  last=max(last,nn[i].x2);
 }
 cout<<ans;
}

Guess you like

Origin blog.csdn.net/weixin_42721412/article/details/108538019