找素数
链接: 找素数.
无非就是循环查找嘛,素数的判断可以先开方来减小运算次数
package lq;
public class 找素数 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int count=0;
int x=2;
while(true){
if(isSu(x))
count++;
if(count==100002)
break;
x++;
}
System.out.println(x);
}
public static boolean isSu(int x){
for(int i=2;i<=Math.sqrt(x);i++){
if(x%i==0)
return false;
}
return true;
}
}
合根植物
链接: 合根植物.
这题主要是对并查集的基础考察。只要知道并查集的模板这题就可以很容易写出来。
并查集讲解可查看链接: 并查集
完整代码:
import java.util.*;
public class 合根植物 {
public static int[]pre;
public static boolean[] plants;
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int m=sc.nextInt();
int n = sc.nextInt();
int k=sc.nextInt();
pre = new int[m*n+1];
for(int i=1;i<=m*n;i++) {
pre[i] = i;
}
plants = new boolean[m*n+1];
//进行合根
for(int i =0;i<k;i++) {
int x = sc.nextInt();
int y = sc.nextInt();
join(x,y);
}
//进行合根植物的标记
for(int i =1;i<=m*n;i++) {
plants[find(i)] = true;
}
//进行植物数量统计
int count = 0;
for(int i =1;i<=m*n;i++) {
if(plants[i])
count++;
}
System.out.println(count);
}
public static int find(int x) {
if(pre[x]!=x) {
return pre[x] = find(pre[x]);
}
return x;
}
public static void join(int x,int y) {
int xx = find(x);
int yy = find(y);
if(xx!=yy) {
pre[yy]=xx;
}
}
}
大胖子走迷宫
链接: 大胖子走迷宫.
用BFS来解决,主要坑的地方就是胖子大小会变,入队也多了一种情况,具体已经注释出来了
import java.util.*;
public class 大胖子走迷宫 {
public static boolean[][] vis;
public static int n;
public static char[][] map;
public static int k;
public static int[] dx = {1,0,-1,0};
public static int[] dy = {0,1,0,-1};
public static class node{
int x,y,t,len;
public node(int x,int y,int t,int len) {
this.x = x;
this.y=y;
this.t = t;
this.len = len;
}
}
public static boolean judge(int x,int y,int len) {
//判断当前情况是否搜过;当前位置是否越界
if(x+len>=n||x-len<0||y+len>=n||y-len<0||vis[x][y]) {
return false;
}
//判断当前位置是否存在障碍
for(int i=x-len;i<=x+len;i++) {
for(int j=y-len;j<=y+len;j++) {
if(map[i][j] == '*')
return false;
}
}
return true;
}
public static int getWei(int t) {
if(t<k) {
return 2;
}
else if(t<2*k)
return 1;
return 0;
}
public static void bfs() {
Queue<node> queue = new LinkedList<>();
queue.offer(new node(3,3,0,5));
vis[2][2] = true;
while(!queue.isEmpty()) {
node temp = queue.poll();
if(temp.x==n-3&&temp.y==n-3) {
System.out.println(temp.t);
}
//有种情况下,比如胖子在‘+’,但周围有‘*’,只要瘦下来就可以通过
if(temp.len!=0) {
queue.offer(new node(temp.x,temp.y,temp.t,getWei(temp.t+1)));
}
for(int i=0;i<4;i++) {
int xx = temp.x+dx[i];
int yy = temp.y+dy[i];
if(judge(xx,yy,temp.len)) {
vis[xx][yy] = true;
queue.offer(new node(xx,yy,temp.t+1,getWei(temp.t+1)));
}
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
k = sc.nextInt();
sc.nextLine();
map = new char[n][n];
vis = new boolean[n][n];
for(int i=0;i<n;i++) {
map[i] =sc.nextLine().toCharArray();
}
bfs();
}
}