64,648
社区成员
发帖
与我相关
我的任务
分享
/********************************************
队列求解问题
********************************************/
#include <iostream>
#include <queue>
using namespace std;
int main()
{
int M,temp;
cin>>M;
int l,r,right,maxright=0,Count=0,j=0; //Count用作区间数记数
queue<int>q1;
int q2; //记录队列的大小
while(cin>>l>>r && !(l==0 && r==0))
{
if(l<=0)
{
if(maxright<r)maxright=r;
}
else
{
q1.push(l);
q1.push(r); //先压右边,后压左边,每次取两元素
}
}
//以上为接受输入,下面每次都将队列中的元素按照maxright作为界限分成两组
//如果上面的答案中每有产生maxright>0,那么可以肯定必然无解
//如果上面的答案中产生的maxright是介于0-M之间的数,继续下面的操作
//如产生的答案中maxright>=M,可以肯定只要一个区间就可以完全覆盖。
if(maxright==0){cout<<"No solution\n";}
else if(maxright>=M){cout<<"1\n";}
//就是用一个队列来存储那些左边比当前右边大的组合,等到后面再继续处理...
else if(maxright>0 && maxright<M)
{
Count=2;
while(!q1.empty())
{
temp=maxright;
q2=q1.size();
while(j<q2)
{
if(q1.front()<=temp)
{
if(!q1.empty()){
q1.pop();
if(q1.front()>maxright){maxright=q1.front();}
q1.pop();
j+=2;}
}
else
{
if(!q1.empty()){
q1.push(q1.front());
q1.pop();
q1.push(q1.front());
q1.pop();
j=j+2;}
}
}
if(maxright==temp){cout<<"No solution\n";break;}
else if(maxright>=M){cout<<Count<<endl;break;}
else if(maxright<M && maxright>temp)
{
Count++;j=0;
}
}
}
return 0;
}
//while(cin>>l>>r && !(l==0 && r==0))
for(l=0,r=1; r<=M; l++,r++)
/********************************************
最小区间覆盖问题
********************************************/
#include <iostream>
#include <queue>
using namespace std;
int main()
{
int M,temp;
cin>>M;
int l,r,maxright=0,Count=0,j=0; //Count用作区间数记数
//所有区间最大右值
int maxofall = 0;
queue<int>q1;
int q2; //记录队列的大小
while(cin>>l>>r && !(l==0 && r==0))
{
if(l<=0)
{
if(maxright<r) maxright=r;
}
else
{
q1.push(l);
q1.push(r); //先压左边,后压右边,每次取两元素
}
if(maxofall<r) maxofall=r;
}
//以上为接受输入,下面每次都将队列中的元素按照maxright作为界限分成两组
//如果上面的答案中没有有产生maxright>0,那么可以肯定必然无解
//如果上面的答案中产生的maxright是介于0-M之间的数,继续下面的操作
//如产生的答案中maxright>=M,可以肯定只要一个区间就可以完全覆盖。
if(maxright==0 || maxofall < M){cout<<"No solution\n";}
else if(maxright>=M){cout<<"1\n";}
//就是用一个队列来存储那些左边比当前maxright大的组合,等到后面再继续处理...
else if(maxright>0 && maxright<M)
{
Count=2;
while(!q1.empty())
{
temp=maxright;
q2=q1.size();
while(j<q2)
{
//左值小于等于0的区间没有用处,这一步只会运行一次...
if(q1.front()<=0)
{
if(!q1.empty()){
q1.pop();
q1.pop();
j+=2;}
}
//左值大于M的区间没有用处,这一步只会运行一次....
else if(q1.front()>M)
{
if(!q1.empty()){
q1.pop();
q1.pop();
j+=2;}
}
//左值大于0但小于等于temp的区间
else if(q1.front()<=temp)
{
if(!q1.empty()){
q1.pop();
if(q1.front()>maxright){maxright=q1.front();}
q1.pop();
j+=2;}
}
//左值大于temp但小于M的区间
else
{
if(!q1.empty()){
q1.push(q1.front());
q1.pop();
q1.push(q1.front());
q1.pop();
j=j+2;}
}
}
if(maxright==temp){cout<<"No solution\n";break;}
else if(maxright>=M){cout<<Count<<endl;break;}
else if(maxright<M && maxright>temp)
{
Count++;j=0;
}
}
}
return 0;
}