蓝桥杯题库 算法提高非vip部分(C++、Java)代码实现(301-400)

将定期更新蓝桥杯习题集的解题报告~

ADV-301 字符串压缩

cpp:

#include <iostream>
using namespace std;
int main() {
    int a[128] = {0}, i = 0;
    string t;
    getline(cin, t);
    while (t[i] != '\0') {
        a[t[i]]++;
        if (a[t[i]] == 1 || a[t[i]] == 3 || a[t[i]] == 6 || t[i] == ' ')
            cout << t[i];
        i++;
    }
    return 0;
}

java:

import java.util.Scanner;
public class Main {
	public static void main(String[] args) {
		new Main().start();
	}
	public void start() {
		Scanner scanner = new Scanner(System.in);
		String string = scanner.nextLine();
		char[] charArray = string.toCharArray();
		int size = 0;
		int[] count = new int[2<<16 - 1];
		for (int i = 0; i < charArray.length; i++) {
			count[charArray[i]] ++;
			if (charArray[i] == ' ' || count[charArray[i]] == 1 || count[charArray[i]] == 3 || count[charArray[i]] == 6) {
				charArray[size++] = charArray[i];
				continue;
			}
		}
		System.out.println(new String(charArray).substring(0, size));
	}
}

ADV-302 秘密行动

cpp:

#include <stdio.h>

int min(int a, int b) { return a < b ? a : b; }

int main() {
    int n;
    int height[10005] = {0};

    scanf("%d", &n);
    for (int i = 1; i <= n; ++i) scanf("%d", &height[i]);

    int f[10005][2] = {0};
    f[1][0] = height[1];
    f[1][1] = 0;
    for (int i = 2; i <= n; ++i) {
        f[i][0] = min(f[i - 1][0], f[i - 1][1]) + height[i];
        f[i][1] = min(f[i - 1][0], f[i - 2][0]);
    }
    printf("%d", min(f[n][0], f[n][1]));

    return 0;
}

java:

import java.util.*;
public class Main {
	static int[] a = new int[100010];
	static int[][] dp = new int[100010][2];
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner cin = new Scanner(System.in);
		int n = cin.nextInt();
		for(int i=1;i<=n;i++)
			a[i] = cin.nextInt();
		dp[1][0]=a[1];	dp[1][1]=0;
		for(int i=2;i<=n;i++) {
			dp[i][0] = Math.min(dp[i-1][0], dp[i-1][1])+a[i];
			dp[i][1] = Math.min(dp[i-1][0], dp[i-2][0]);
		}
		System.out.println(Math.min(dp[n][0], dp[n][1]));
	}

}

ADV-303 数组求和

cpp:

#include <algorithm>
#include <iostream>
#include <string>

using namespace std;

int main() {
    int n;
    cin >> n;
    int m;
    cin >> m;
    int *arr = new int[n];
    for (int i = 0; i < n; i++) cin >> arr[i];
    int max = 0;
    for (int begin = 0, end = begin + m - 1; begin < n; begin++, end++) {
        int sum = 0;
        for (int i = begin; i <= end; i++) sum += arr[i % n];
        max = max > sum ? max : sum;
    }
    cout << max;
    system("pause");
    return 0;
}

java:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
	
 public static void main(String[] args) throws IOException{
	 BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		String[] split1 = br.readLine().split(" ");
		String[] split2 = br.readLine().split(" ");
		br.close();
		int n=Integer.parseInt(split1[0]);
		int m=Integer.parseInt(split1[1]);
		int []arr=new int [n];
		for (int i = 0; i < n; i++) {
			arr[i]=Integer.parseInt(split2[i]);
		}
		int max=0;
		for(int i=0;i<m;i++) {
			max+=arr[i];
		}
	    for(int i=0;i<n;i++) {
	    	int sum=0;
	    	for(int j=0;j<m;j++) {
	    		int p=i+j;
	    		if(p>=n) {
	    			p-=n;
	    		}
	    		sum+=arr[p];
	    	}
	    	max=sum>max?sum:max;
	    }
		System.out.println(max);
}
}

ADV-304 矩阵转置

cpp:

#include <iostream>
using namespace std;
int main() {
    int n, m;
    cin >> n >> m;
    int i, j;
    int arr[25][25];
    for (i = 0; i < n; i++) {
        for (j = 0; j < m; j++) {
            cin >> arr[i][j];
        }
    }
    for (i = 0; i < m; i++) {
        for (j = 0; j < n; j++) {
            cout << arr[j][i] << " ";
        }
        cout << endl;
    }
    return 0;
}

java:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
       int n=sc.nextInt();
       int m=sc.nextInt();
       sc.nextLine();
       int[][] temp=new int[n][m];
       for(int i=0;i<n;i++){
           for(int j=0;j<m;j++){
               temp[i][j]=sc.nextInt();
           }
           sc.nextLine();
       }
       int[][] result=new int[m][n];
       for(int i=0;i<n;i++)
           for(int j=0;j<m;j++)
               result[j][i]=temp[i][j];
       for(int i=0;i<m;i++) {
           for (int j = 0; j < n; j++)
               System.out.print(result[i][j]+" ");
           System.out.println();
       }
    }
}

ADV-305 输出二进制表示

cpp:

#include <cstring>
#include <iostream>

using namespace std;
int main() {
    int n, i;
    cin >> n;
    for (i = 7; i >= 0; i--) cout << (n >> i & 1);
    return 0;
}

java:


import java.math.BigInteger;
import java.util.*;

public
class Main {
   public
    static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int n = input.nextInt();
        int v = n;
        String s = "";
        for (int i = 0; i < 7; i++) {
            s = (n & 1) + s;
            n = n >> 1;
        }
        if (v >= 0)
            System.out.print(0 + s);
        else
            System.out.print(1 + s);
    }
}

ADV-306 输出三个整数的最大数

cpp:

#include <iostream>
using namespace std;
int main() {
    int a, b, c, d;
    cin >> a >> b >> c;
    d = (a > b) ? a : b;
    d = (c > d) ? c : d;
    cout << d;
    return 0;
}

java:

import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int a = sc.nextInt();
		int b = sc.nextInt();
		int c = sc.nextInt();
		int max = a>b ? a:b;
		max = max>c ? max:c;
		System.out.println(max);
	}
}

ADV-307 vertex cover

cpp:

#include <stdio.h>
#include <map>
#include <vector>

const int MAX_VERTEX = 100;
// 测试次数,点数,边数,限制的k,如果不能得到小于k的结果,就输出-1
int num_of_test, num_of_vertex, num_of_edge, k;
// 存储最优的点的信息
std::vector<int> result_vertex_list;

// 处理度为1的结点
void deal_with_degree_one(std::map<int, std::map<int, int> > &info,
                          std::map<int, int> &searched, int &checked_vertex,
                          int &checked_edge) {
    bool flag = true;
    int tmp;
    int length;
    while (flag) {
        flag = false;
        for (std::map<int, std::map<int, int> >::iterator iter = info.begin();
             iter != info.end();) {
            length = iter->second.size();
            if (length == 1) {
                // 增加search过的边和元素
                tmp = iter->second.begin()->first;
                if (searched.count(tmp) == 0) ++checked_vertex;
                // iter->second.erase(tmp);
                searched[tmp] = 1;
                // 必定加入的点要删除所有相关的点
                for (std::map<int, int>::iterator iter1 = info[tmp].begin();
                     iter1 != info[tmp].end();) {
                    info[iter1->first].erase(tmp);
                    ++checked_edge;
                    info[tmp].erase(iter1++);
                }
                // 删除边和元素
                info.erase(iter++);
                flag = true;
            } else if (length == 0) {
                info.erase(iter++);
            } else {
                ++iter;
            }
        }
    }
}

//遍历
void dfs(int index, int *minimum, int checked_vertex, int checked_edge,
         std::map<int, std::map<int, int> > &info,
         std::map<int, int> &searched) {
    // 标记此点已经检查过
    searched[index] = 1;
    // 如果加上该点已经检查过比minimum多的点,则不可能更优了,返回
    if (checked_vertex + 1 >= *minimum) {
        searched.erase(index);
        return;
    }
    // 假如加入该点
    // 如果已经覆盖了全部的边
    if (checked_edge + info[index].size() == num_of_edge) {
        if (checked_vertex + 1 < *minimum) {
            *minimum = checked_vertex + 1;
            result_vertex_list.clear();
            for (std::map<int, int>::iterator iter = searched.begin();
                 iter != searched.end(); iter++)
                result_vertex_list.push_back(iter->first);
        }
        searched.erase(index);
        return;
    }
    // 存储修改后的变量
    std::map<int, std::map<int, int> > tmp_info, tmp_info_not;
    std::map<int, int> tmp_searched, tmp_searched_not;
    int tmp_checked_vertex = checked_vertex,
        tmp_checked_vertex_not = checked_vertex;
    int tmp_checked_edge = checked_edge, tmp_checked_edge_not = checked_edge;
    for (std::map<int, std::map<int, int> >::iterator iter = info.begin();
         iter != info.end(); iter++) {
        tmp_info[iter->first] = iter->second;
        tmp_info_not[iter->first] = iter->second;
    }
    for (std::map<int, int>::iterator iter = searched.begin();
         iter != searched.end(); iter++) {
        tmp_searched[iter->first] = iter->second;
        tmp_searched_not[iter->first] = iter->second;
    }
    // 如果使用该点
    // 删除本点的信息和其他点的关于该点的信息,修改相关信息
    ++tmp_checked_vertex;
    tmp_checked_edge += info[index].size();
    for (std::map<int, int>::iterator iter = info[index].begin();
         iter != info[index].end(); iter++)
        tmp_info[iter->first].erase(index);
    tmp_info.erase(index);
    // 处理度为1的点
    deal_with_degree_one(tmp_info, tmp_searched, tmp_checked_vertex,
                         tmp_checked_edge);
    // 如果找到了所需要的边数
    if (tmp_checked_edge == num_of_edge) {
        if (tmp_checked_vertex < *minimum) {
            *minimum = tmp_checked_vertex;
            result_vertex_list.clear();
            for (std::map<int, int>::iterator iter = tmp_searched.begin();
                 iter != tmp_searched.end(); iter++)
                result_vertex_list.push_back(iter->first);
        }
        searched.erase(index);
        return;
    }
    // 寻找下一个最大度数的点
    bool found = false;
    int temp_index = 0, tmp_max_length = 0, tmp_second_max_length = 0;
    for (std::map<int, std::map<int, int> >::iterator iter = tmp_info.begin();
         iter != tmp_info.end(); iter++) {
        if (tmp_searched.count(iter->first) == 0) {
            int tmp_length = iter->second.size();
            if (tmp_length > tmp_max_length) {
                found = true;
                temp_index = iter->first;
                tmp_second_max_length = tmp_max_length;
                tmp_max_length = tmp_length;
            } else if (tmp_length > tmp_second_max_length) {
                tmp_second_max_length = tmp_length;
            }
        }
    }
    int weight;
    if (*minimum - tmp_checked_vertex <= 2) {
        weight = tmp_max_length * (*minimum - tmp_checked_vertex - 1);
    } else {
        weight = tmp_max_length +
                 tmp_second_max_length * ((*minimum - tmp_checked_vertex - 2));
    }
    if (weight >= num_of_edge - tmp_checked_edge) {
        dfs(temp_index, minimum, tmp_checked_vertex, tmp_checked_edge, tmp_info,
            tmp_searched);
    }
    // 如果不使用该点,那么所有与该点相邻的点都必须被使用,否则必存在着边无法被消去
    // 消去该点相邻的点
    // 本点不被使用
    tmp_searched_not.erase(index);
    // 找到该点相邻的点
    for (std::map<int, int>::iterator iter = info[index].begin();
         iter != info[index].end(); iter++) {
        // 删除tmp_info_not中的该点相邻的点,标记使用
        tmp_searched_not[iter->first] = 1;
        ++tmp_checked_vertex_not;

        for (std::map<int, int>::iterator iter1 = info[iter->first].begin();
             iter1 != info[iter->first].end(); iter1++) {
            // 如果该边还未在之前其他点的时候被删除
            if (tmp_info_not.count(iter1->first) > 0) {
                tmp_info_not[iter1->first].erase(iter->first);
                tmp_info_not[iter->first].erase(iter1->first);
                ++tmp_checked_edge_not;
            }
        }
        tmp_info_not.erase(iter->first);
    }
    // 处理度为1的点
    deal_with_degree_one(tmp_info_not, tmp_searched_not, tmp_checked_vertex_not,
                         tmp_checked_edge_not);
    // 如果找到了所需要的边数
    if (tmp_checked_edge_not == num_of_edge) {
        if (tmp_checked_vertex_not < *minimum) {
            *minimum = tmp_checked_vertex_not;
            result_vertex_list.clear();
            for (std::map<int, int>::iterator iter = tmp_searched_not.begin();
                 iter != tmp_searched_not.end(); iter++)
                result_vertex_list.push_back(iter->first);
        }
        searched.erase(index);
        return;
    }
    // 寻找下一个最大度数的点
    found = false;
    temp_index = 0, tmp_max_length = 0, tmp_second_max_length = 0;
    for (std::map<int, std::map<int, int> >::iterator iter =
             tmp_info_not.begin();
         iter != tmp_info_not.end(); iter++) {
        if (tmp_searched_not.count(iter->first) == 0) {
            int tmp_length = iter->second.size();
            if (tmp_length > tmp_max_length) {
                found = true;
                temp_index = iter->first;
                tmp_second_max_length = tmp_max_length;
                tmp_max_length = tmp_length;
            } else if (tmp_length > tmp_second_max_length) {
                tmp_second_max_length = tmp_length;
            }
        }
    }
    if (*minimum - tmp_checked_vertex <= 2) {
        weight = tmp_max_length * (*minimum - tmp_checked_vertex - 1);
    } else {
        weight = tmp_max_length +
                 tmp_second_max_length * ((*minimum - tmp_checked_vertex - 2));
    }
    if (weight >= num_of_edge - tmp_checked_edge) {
        dfs(temp_index, minimum, tmp_checked_vertex_not, tmp_checked_edge_not,
            tmp_info_not, tmp_searched_not);
    }
    searched.erase(index);
    return;
}

int main() {
    // 读取的边
    int u = 0, v = 0;
    // 记录已经寻找到的点数, 边数
    int checked_vertex, checked_edge;
    // 保存边的信息
    std::map<int, std::map<int, int> > info;
    // 保存已经搜索的点的信息
    std::map<int, int> searched;
    // 开始读取
    scanf("%d", &num_of_test);
    for (int i = 0; i < num_of_test; i++) {
        info.clear();
        searched.clear();
        result_vertex_list.clear();
        scanf("%d %d %d", &num_of_vertex, &num_of_edge, &k);
        // 初始化
        checked_vertex = 0, checked_edge = 0;
        // 读取数据
        for (int j = 0; j < num_of_edge; j++) {
            scanf("%d %d", &u, &v);
            info[u][v] = 1;
            info[v][u] = 1;
        }
        // 处理度为1的点
        deal_with_degree_one(info, searched, checked_vertex, checked_edge);
        // 需要传送的参数
        int minimum = k + 1;
        // 如果去除了为1的点之后已经所有的边都去掉了
        if (checked_edge == num_of_edge) {
            if (checked_vertex < minimum) {
                minimum = checked_vertex;
                result_vertex_list.clear();
                for (std::map<int, int>::iterator iter = searched.begin();
                     iter != searched.end(); iter++)
                    result_vertex_list.push_back(iter->first);
            }
        } else {
            // 仍然有边剩余,进行处理
            // int minimum = k+1;
            int temp_index = 0, tmp_max_length = 0;
            for (std::map<int, std::map<int, int> >::iterator iter =
                     info.begin();
                 iter != info.end(); iter++) {
                if (searched.count(iter->first) == 0) {
                    int tmp_length = iter->second.size();
                    if (tmp_length > tmp_max_length) {
                        temp_index = iter->first;
                        tmp_max_length = tmp_length;
                    }
                }
            }
            dfs(temp_index, &minimum, checked_vertex, checked_edge, info,
                searched);
        }
        // 如果找不到小等于k个节点的情况则输出-1,否则输出点数和一种结果的情况
        if (minimum > k) {
            printf("%d\n", -1);
        } else {
            printf("%d\n", minimum);
            for (std::vector<int>::iterator iter = result_vertex_list.begin();
                 iter != result_vertex_list.end(); iter++)
                printf("%d ", *iter);
            printf("\n");
        }
    }
    return 0;
}

ADV-308 递归输出

cpp:

#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <queue>
#include <string>
using namespace std;
#define ll long long
void dfs(int n) {
    if (n) {
        dfs(n / 10);
        cout << n % 10 << "-";
    }
    return;
}
int main() {
    int n;
    cin >> n;
    dfs(n);
    return 0;
}

java:

import java.util.Scanner;

public class Main {

	public static void main(String[] agrs) {
		Scanner in = new Scanner(System.in);
		String str = in.next();
		f(str);
	}

	private static void f(String str) {
		for (int i = 0; i < str.length(); i++) {
			System.out.print(str.charAt(i) + "-");
		}
	}

}

ADV-309 进制转换

cpp:

#include <bits/stdc++.h>
using namespace std;
int main(int argc, char** argv) {
    int n, ret = 0, ret2 = 0;
    vector<int> res;
    cin >> n;
    while (n) {
        res.push_back(n % 8);
        n /= 8;
    }
    string outstr;
    int len = res.size();
    for (int i = len - 1; i >= 0; i--) {
        outstr = outstr + char(res[i] + '0');
    }
    if (0 != len)
        cout << 0 << outstr;
    else {
        cout << 0;
    }

    return 0;
}

java:

import java.util.*;

public class Main{
 	public static void main(String[] args) {
	    Scanner in = new Scanner(System.in);
	    int a = in.nextInt();
	    if(a==0) {
	    	System.out.println(0);
	    	return;
	    }
	    int s[] = new int[8];
	    int k=0;
	    while(a>0) {
	    	s[k] = a%8;
	    	a=a/8;
	    	k++;
	    }
	    for(int i = k>2? k:2; i>=0; i--) {
	    	System.out.print(s[i]);
	    }
 	}
}

ADV-310 哥德巴赫猜想

cpp:

#include <iostream>
using namespace std;

bool IsPrime(int n);

int main() {
    int n;
    cin >> n;
    for (int i = 6; i < n; i++) {
        if (i % 2 == 0)
            for (int j = 2; j <= i - 2; j++) {
                if (IsPrime(j) && IsPrime(i - j)) {
                    cout << i << "=" << j << "+" << i - j << endl;
                    break;
                }
            }
    }
}

bool IsPrime(int n) {
    for (int j = 2; j < n - 1; j++)
        if (n % j == 0) return 0;
    return 1;
}

ADV-311 猴子吃桃问题

cpp:

#include <fstream>
#include <iostream>
using namespace std;
void checkAnswer();
int GetNumber(int n) {
    int sum = 1;
    for (int i = 0; i < n - 1; i++) {
        sum = (sum + 1) * 2;
    }
    return sum;
}
int main() {
    int n;
    cin >> n;
    cout << GetNumber(n) << endl;
}

ADV-312 圆的周长与面积

cpp:

#include <stdio.h>
#include <string.h>
int main() {
    int n, i;
    double r;
    scanf("%lf", &r);
    printf("%g\n%g", 3.14 * 2 * r, 3.14 * r * r);
    return 0;
}

ADV-313 字符串顺序比较

cpp:

#include <algorithm>
#include <cmath>
#include <cstdio>
#include <iostream>
#include <numeric>
#include <string>
#include <vector>
using namespace std;
int main() {
    string a, b;
    cin >> a >> b;
    int sum = 0;
    if (b.size() > a.size()) swap(a, b);
    for (int i = 0; i < a.size(); i++) {
        if (i <= a.size() - 1 && i <= b.size() - 1) {
            sum += a[i] - b[i];
        } else {
            sum += a[i];
        }
    }
    if (sum > 0) cout << -1 << endl;
    if (sum < 0) cout << 1 << endl;
    if (sum == 0) cout << 0 << endl;
    return 0;
}

java:

import java.util.*;

public
class Main {
    static StringBuffer buf = new StringBuffer();
   public
    static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str1 = sc.next();
        String str2 = sc.next();
        char[] st1 = str1.toCharArray();
        char[] st2 = str2.toCharArray();
        int a = str1.length();
        int b = str2.length();
        int flag = 0;
        if (a > b) {
            for (int i = 0; i < a; i++) {
                if (st1[i] < st2[i]) {
                    flag = 1;
                    break;
                }
                if (st1[i] > st2[i]) {
                    flag = -1;
                    break;
                }
            }
        } else {
            for (int i = 0; i < b; i++) {
                if (st1[i] < st2[i]) {
                    flag = 1;
                    break;
                }
                if (st1[i] > st2[i]) {
                    flag = -1;
                    break;
                }
            }
        }
        System.out.println(flag);
    }
}
发布了234 篇原创文章 · 获赞 159 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/qq_36306833/article/details/104718456