Example
input
Copy
8 10 3 3 6 8 6 2 2 5 20 3 3 7 12 41 5 1 11 21 31 41 10 5 2 4 6 8 10 5 5 3 2 5 4 1 1000000000 1 1 1000000000 4 1 1000000000 10 16
output
Copy
7 5 11 28 9 5 2 15
题目大意:有n个房子围成一个环,其中有m个房子被病毒感染,每一天可以选择一个未被感染的房子保护,以后将不会被感染,而其他没有被保护的房子,如果和一个被感染的房子相邻且在之前没有被保护就会被感染,需要注意的是每一天都是先选择要保护的房子,然后病毒才会扩散,问最终被感染的房子最少有多少。
解题思路:因为n非常大,所以遍历所有房子来处理肯定是不行的,但是被感染的房子最多只有1e5个,所以我们应该根据已经被感染的房子将整个环中未被感染的房子划分成段,然后贪心地来处理每一段,算出最多能保护多少房子不被感染,那应该怎么贪心呢?正确的贪心策略应该是这样的,我们从大到小枚举所有区间,根据选择的顺序可以确定这段区间在之前已经有多少房子被感染了,然后就可以确定能够保护多少房子,至于为什么要从大到小来枚举整个区间,是因为当一个小区间全部被感染之后就不能再感染了,而大区间可能一直在感染,所以优先阻止大区间病毒的扩散一定是最优的。
上代码:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <map>
using namespace std;
const int N=1E5+10;
int a[N],n,m;
struct node_{
int l;
int r;
}h;
int num[N];
bool cmp(int x,int y)
{
return x>y;
}
int main()
{
int t;
cin>>t;
while(t--)
{
cin>>n>>m;
for(int i=1;i<=m;i++)
cin>>a[i];
if(m==1)
{
if(n==1)
cout<<1<<endl;
else if(n>1)
cout<<2<<endl;
continue;
}
sort(a+1,a+1+m);
int cnt=0;
for(int i=2;i<=m;i++)
{
if(a[i]==a[i-1]+1)
continue;
int l=a[i-1]+1,r=a[i]-1;
num[++cnt]=r-l+1;
}
num[++cnt]=n-a[m]+a[1]-1;
sort(num+1,num+cnt+1,cmp);
int res=0,ans=0;
for(int i=1;i<=cnt;i++)
{
if(num[i]<=res)
break;
int time=0;//记录拯救这段区间需要花费几天
int temp=num[i]-res;
temp--;
ans++;
time++;
temp--;
temp=max(temp,0);
if(temp)
time++;
ans+=temp;
res+=time*2;//记录因先拯救其他区间而导致被感染的房子数量
}
cout<<n-ans<<endl;
}
return 0;
}