1.扫地机器人
参考扫地机器人
#include <iostream>
#include <cmath>
#include <algorithm>
using namespace std;
const int N=1e5+100;
int a[N];
int n,k;
bool check(int x){
//r表示机器人已经扫到的区域右边界
int r=0;
for(int i=0;i<k;i++){
if(a[i]-x>r)return false;// 不能无缝衔接扫地区域,则一定失败
else{
if(a[i]<=r)r=a[i]+x-1;// 在区域内,则从本区域开始,能扫到的最远区域
else r+=x; // 在区域外,则直接从边界累加
}
}
// 判断是否能扫完整个区域
return r>=n;
}
int main()
{
scanf("%d%d",&n,&k);
for(int i=0;i<k;i++){
scanf("%d",&a[i]);
}
//这里排序不是因为二分需要单调,而是贪心的要求
sort(a,a+k);
//二分查找机器人扫描范围,二分性质满足贪心,当大于等于该范围时一定可以扫描全部,但是时间更长
//选择满足性质的边界的二分查找
int l=0,r=n;
while(l<r){
int mid=l+r>>1;
if(check(mid))r=mid;
else l=mid+1;
}
//输出总查找时间
printf("%d",2*(l-1));// 花费时间 = 2 × (扫地范围 - 1)
return 0;
}
2.全球变暖
连通块问题 dfs或者bfs搜
#include<cstdio>
#include<algorithm>
#include<queue>
#define x first
#define y second
using namespace std;
typedef pair<int, int> pii;
const int N = 1e3 + 10;
int n;
char g[N][N];
bool st[N][N];
bool path[N][N];
int dx[4] = {-1, 1, 0, 0}; //四个方位
int dy[4] = {0, 0, -1, 1};
void bfs(int sx, int sy, int &total, int &bound) {
queue<pii> q;
q.push({sx, sy});
path[sx][sy] = true;
while (!q.empty()) {
pii t = q.front();
q.pop();
total++;
bool is_bound = false;
for (int i = 0; i < 4; i++) {
int x = t.x + dx[i], y = t.y + dy[i];
if (x < 0 || x >= n || y < 0 || y >= n) {
continue;
}
if (path[x][y]) {
continue;
}
if (g[x][y] == '.') {
is_bound = true; //这个块是周围有海的块
continue;
}
q.push({x, y});
path[x][y] = true;
}
if (is_bound) {
bound++; //当前岛屿总的周围有海的块的数量
}
}
}
int main() {
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%s", g[i]);
}
int cnt = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (!path[i][j] && g[i][j] == '#') {
int total = 0, bound = 0; //这个岛屿所有的块的数量, 这个岛屿上周围是海的块的数量
bfs(i, j, total, bound);
if (total == bound) { // 当前的块中所有的格子==周围有海洋的数量, 就会被淹没
cnt++;
}
}
}
}
printf("%d\n", cnt);//被淹没的数量
return 0;
}
3.机器人行走
#include <iostream>
#include <cmath>
#include <algorithm>
using namespace std;
int dx[4]={1,0,-1,0},dy[4]={0,1,0,-1};
int main()
{
int n;
cin>>n;
for(int i=0;i<n;i++){
string str;
cin>>str;
int startx=0,starty=0,dis=0,dir=0;
int len=str.size();
for(int j=0;j<len;j++){
int sum=0;
bool flag=false;
while(str[j]>='0'&&str[j]<='9'){
sum*=10;
sum+=str[j++]-'0';
flag=true;
}
//printf("sum=%d\n",sum);
if(flag)j--;
startx+=sum*dx[dir],starty+=sum*dy[dir];
if(str[j]=='L')dir=(dir-1+4)%4;
if(str[j]=='R')dir=(dir+1)%4;
}
//printf("x==%d,y==%d\n",startx,starty);
printf("%.2f\n",sqrt(startx*startx+starty*starty));
}
return 0;
}
4.数的幂次
#include <iostream>
using namespace std;
long long qmi(long long n,long long m,long long p){
long long res=1%p;
while(m){
if(m&1)res=res*n%p;
n=n*n%p;
m>>=1;
}
return res;
}
int main()
{
long long n,m,p;
int t;
scanf("%lld",&t);
while(t--){
scanf("%lld%lld%lld",&n,&m,&p);
printf("%lld\n",qmi(n,m,p));
}
return 0;
}