提高级-算法总结--思维广搜3+二分
fly_bamboo · · 算法·理论
嗨嗨嗨,该 shi 的广搜又来啦!
P7243 最大公约数
这道题是 BFS 你信吗?
我们这样考虑。广搜是求最短步数,我们也是否可以拿他求最短天数?
首先我们每天都向四方蔓延,然后更新
无解是什么情况?
整体
其实不难,主要是题意恶心:
#include<bits/stdc++.h>
#define int long long
using namespace std;
int a[2005][2005];
bool vis[2005][2005];
int qx,qy,n,m;
int gcd(int a,int b)
{
if(b==0) return a;
return gcd(b,a%b);
}
int head=0,tail=1;
struct node
{
int x,y,step;
}q[4000005];
bool check(int x,int y)
{
if(x<1||x>n||y<1||y>m) return false;
if(vis[x][y]==true) return false;
return true;
}
void work(int x,int y,int step)
{
if(check(x,y))
{
head++;
q[head].x=x;
q[head].y=y;
q[head].step=step;
vis[x][y]=true;
a[qx][qy]=gcd(a[qx][qy],a[x][y]);
if(a[qx][qy]==1)
{
cout<<step;
exit(0);
}
}
return;
}
void bfs()
{
head++;
q[head].x=qx;
q[head].y=qy;
q[head].step=0;
vis[qx][qy]=true;
while(head-tail+1>0)
{
int x=q[tail].x;
int y=q[tail].y;
int step=q[tail].step;
tail++;
work(x-1,y,step+1);
work(x+1,y,step+1);
work(x,y-1,step+1);
work(x,y+1,step+1);
}
return;
}
signed main()
{
cin>>n>>m;
int Gcd=0;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
cin>>a[i][j];
if(Gcd==0) Gcd=a[i][j];
else Gcd=gcd(Gcd,a[i][j]);
}
}
if(Gcd>1)
{
cout<<-1;
return 0;
}
cin>>qx>>qy;
if(a[qx][qy]==1)
{
cout<<0;
return 0;
}
bfs();
return 0;
}
U408367 指导
又到了可恶的齐芒原创题环节了!
这道题其实是二分,你知道为什么吗?
因为单调性臭名昭著
我们二分教完所有学生的时间。
首先,
其次,我们得到了结果,去看是哪个老师教小莱。
我们看哪个老师在结束时恰好教完,先计算已经教了多少人,他就接着教,一直教到小莱,输出答案。
最难的就在于处理后面的过程,具体可以参考代码:
#include<bits/stdc++.h>
#define int long long
using namespace std;
int n,m;
int a[1000005];
bool check(int x)
{
int cnt=0;
for(int i=1;i<=n;i++) cnt+=(x+a[i]-1)/a[i];
return cnt>=m;
}
signed main()
{
cin>>n>>m;
for(int i=1;i<=n;i++) cin>>a[i];
int l=-1,r=m*10000000+1;
while(l+1<r)
{
int mid=(l+r)/2;
if(check(mid)==true) r=mid;
else l=mid;
}
l++;
int lst=0;
for(int i=1;i<=n;i++) lst+=(l-2+a[i])/a[i];
for(int i=1;i<=n;i++)
{
if((l-1)%a[i]==0)
{
lst++;
if(lst==m)
{
cout<<i;
return 0;
}
}
}
return 0;
}
下课!
收工!