Algorithm questions-C++/python (6)

I got stronger, but still not enough...

Maybe it's because the written test questions have become weaker.

  1. Scholarship AC

If there is a failing course, that is, the score is less than 60, you will not be able to get a scholarship, and output "No"

If there is no failure, calculate the mean of all scores and compare with the standard, if it is greater than or equal to the standard score, output "Yes", otherwise output "No"

Calculate the average score: (sum (single subject score * credits)) / (sum of credits)

Input: number of data sets, total number of subjects in a set of data + standard scores, credits for each subject, scores for each subject

Output: "Yes"/"No"

#include<bits/stdc++.h>
using namespace std;
int t;
const int N = 1005;
int n,avg;
int s[N];
int f[N];
int main()
{
    
    
	cin>>t;
	while(t--)
	{
    
    
		scanf("%d%d",&n,&avg);
		int target = 0,SUM = 0;
		bool flag = false;
		for(int i=0;i<n;i++)
		{
    
    
			scanf("%d",&s[i]);
			SUM+=s[i];
		}
		for(int i=0;i<n;i++)
		{
    
    
			scanf("%d",&f[i]);
			if(f[i]>=60)
				target+=f[i]*s[i];
			else{
    
    
				flag = true;
			}
		}
		if(flag == false)
		{
    
    
			if(target/SUM >= avg)
				cout<<"Yes"<<endl;
			else
				cout<<"No"<<endl;
		}
		else
		{
    
    
			cout<<"No"<<endl;
		}
	}
	return 0;
 } 

  1. Xiaomei throws dice without violence. 0.27
    Time limit: 1000MS
    Memory limit: 65536KB
    Title description:
    Xiaomei needs to make a dice. Different from the general six-sided dice, Xiaomei needs a total of n sides of the dice, and the numbers on each side are also different from the general ones. The numbers on the n sides need to be a1, a2,...an respectively. Of course, the dice is a positive n-hedron, and the only legal requirement is that the sum of all opposite sides needs to be equal, such as a six-sided dice with numbers 1, 2, 3, 4, 2, 3, then the above 1, 4 on the bottom, 2 on the front, 3 on the back, 2 on the left, and 3 on the right are legal solutions.
    Because there are many options, Xiaomei doesn't care how to make such a dice. Xiaomei just wants to know whether she can make a legal dice. Of course, n is guaranteed to be even.
    Input description:
    The first line is an integer T, indicating the number of query data sets.
    For each group of queries:
    the first line is a positive integer n, indicating the number of sides of the dice.
    The next line contains n integers in each line, which are a1, a2,..., an.
    Let N = the sum of n of all query data.
    For all data, 1≤T≤100, 1≤N≤105, 1≤ai≤105, n is an even number.
    Output description:
    For each group of queries, output "YES" or "NO" (without quotation marks) to indicate whether the dice can be spelled or not.

    C++ garbage violence, directly judged by special conditions

#include<bits/stdc++.h>
using namespace std;
int t;
int n;
const int N=105;
int a[N];
long long SUM;
int main()
{
    
    
	cin>>t;
	while(t--)
	{
    
    
		cin>>n;
		if(n%2==1)
		{
    
    
			cout<<"NO"<<endl;
			continue;
		} 
		else if(n==2)
		{
    
    
			cout<<"YES"<<endl;
			continue;
		}
		for(int i=0;i<n;i++)
		{
    
    
			scanf("%d",&a[i]);
			SUM+=a[i];
		}
		long long c = n/2;
		if(SUM % c==0) cout<<"YES"<<endl;
		else cout<<"NO"<<endl;
		// 任选两个数 和为固定值... 
	}
	return 0;
}

If you can’t write it out, you can use python directly

# 排序 加和==n+1
def solve(n, a):
    # 将数字按照从小到大的顺序排列
    a.sort()
    # 判断每组相对的数字之和是否相等
    for i in range(n//2):
        if a[i]+a[n-1-i] != a[0]+a[n-1]:
            return "NO"
    # 判断每个数字的相对数字是否符合要求
    cnt = [0] * (n+1)
    for i in range(n):
        j = n-1-i
        cnt[a[i]] += 1
        cnt[a[j]] += 1
        if cnt[a[i]] != cnt[a[j]]:
            return "NO"
    return "YES"

n = int(input())
a = list(map(int, input().split()))
print(solve(n, a))
  1. Farming AC

    There are N kinds of crops, their purchase value is ai, their selling value is bi, and the number of days to mature is ti.

    There is a piece of land that can be planted for M days. What is the maximum value that can be obtained after M days?

    Well, for the complete knapsack board question, just write it directly, and don't analyze it.

#include<bits/stdc++.h>
using namespace std;
int n,m;
const int N = 1e6;
int a[N],b[N],t[N],c[N]; 
int f[N];
int main()
{
    
    
	cin>>n>>m;
	for(int i=0;i<n;i++)
		scanf("%d",&t[i]);
	for(int i=0;i<n;i++)
		scanf("%d",&a[i]);
	for(int i=0;i<n;i++)
	{
    
    
		scanf("%d",&b[i]);	
		c[i] = b[i]-a[i];
	}
	// 完全背包? 
	for(int i=0;i<n;i++)
	{
    
    
		for(int j=t[i];j<=m;j++)
			f[j] = max(f[j],f[j-t[i]]+c[i]);
	}
	cout<<f[m]<<endl;
	return 0;
}
  1. Delete 01 string 0.27 Just started to do it, I feel that the underworld is another tricky question
    Time limit: 1000MS
    Memory limit: 65536KB
    Title description:
    Xiaomei will give you a 01 string of length n (a string containing only characters 0 and 1), you You can delete a prefix and a suffix of this string (can be empty), that is, keep a continuous substring of the original string. After the operation, the cost of the entire string is the sum of the following two parts:

    (1) The number of deleted characters 1;
    (2) The number of characters 0 in the remaining substring
    You need to minimize the cost of the operation and output it.
    Input description:
    Input only one line, a string of 01 with a length of n.
    For all data, 1≤n≤105
    output description:
    output only one line, an integer, representing the minimum operation cost.

    The idea is to split the target string into three parts: prefix, intermediate string, and suffix

    The prefix counts the number of 1, the suffix counts the number of 1 -> delete 1 has a cost

    Count the number of 0s in the middle substring -> keep the cost of 0

    s = input()
    def min_cost(s):
        n = len(s)
        ans = float('inf')
        zeros = s.count('0')
        ones = s.count('1')
        if zeros == 0 or ones == 0 or zeros == n:
            return 0
        # 只删除前缀或后缀的情况
        ans = min(ans, s.count('0'))# cost = 子串里有0个数
        for i in range(n):
            for j in range(n-1, i,-1):
                cost = s[:i].count('1') + s[j:n-1].count('1')
                if i < j:
                    cost += s[i:j].count('0')
                ans = min(ans, cost)
        return ans
    
    print(min_cost(s))
    
    // 用python写出来了 这里可以用c++改装一下
    #include<bits/stdc++.h>
    using namespace std;
    // algorithm里面有count函数 可以统计string里的字符个数 
    int min_cost(string s) {
          
          
        int n = s.size();
        int ans = INT_MAX;
        int c0 = 0;
        for (char c : s) {
          
          
        	if(c=='0') c0+=1;
        }
        if (c0 == 0 || c0 == n) {
          
          
            return 0;
        }
        ans = min(ans, c0); // 只删除前缀或后缀的情况
        for (int i = 0; i < n; i++) {
          
          
            for (int j = n-1; j >=0; j--) {
          
          
                int cost = count(s.begin(), s.begin()+i, '1') // 前缀的1个数 
                         + count(s.begin()+j, s.end(), '1'); // 后缀的1个数 
                if (i < j) {
          
          
                    cost += count(s.begin()+i, s.begin()+j, '0');// 中间串的0个数 
                }
                ans = min(ans, cost);
            }
        }
        return ans;
    }
    
    int main() {
          
          
        string s;
        cin >> s;
        cout << min_cost(s) << endl;
        return 0;
    }
    
  2. Xiaomei playing competition 0.18
    Time limit: 1000MS
    Memory limit: 65536KB
    Title description:
    Xiaomei is participating in a competition.

    There are a total of 2^k individuals participating in this competition (including Xiaomei), numbered 1,2,...,2^k, and everyone is in the same group at the beginning. The procedure of the competition is as follows: Assuming that there are n people in the current group (n is an even number), then the first n/2 people are divided into a new group, and the last n/2 people are divided into a new group, and then the two groups are divided into two groups. Competition, determine their respective winners, and then the winners of the two groups will compete, the winner will be the winner of the current group until the winner of the original group is determined. Of course a person's group winner must be himself.

    For example, if there are 4 people in the current group, numbered 1, 2, 3, 4, then 1, 2 will be divided into a group, 3, 4 will be divided into a group to compete separately, and then the winner of 1, 2 and 3 , The winners of the 4 will compete again to determine the winner of the entire group.

    Since everyone has different abilities, Xiaomei predicted the winners of everyone's two-two competition, and now Xiaomei wants to know who the final winner is.

    Input description
    The first line is a positive integer k, indicating that the total number of people is 2^k.

    Next 2^k lines, the i-th line contains 2^k integers.

    Where v[i,j]=i or j represents the winner of the competition between i and j.

    For all data, 1≤k≤8, 1≤v[i,j]≤2^k

    Output description
    Output an integer representing the number of the final winner.

    No ideas, just dishes.

    I asked chatgpt to write it later, but I modified it myself, and it will make mistakes when it writes itself.

    A simple recursion plus two points will suffice.

    Test Data:

    2
    1 2 3 1
    2 2 3 2
    3 3 3 3
    1 2 3 4

    Output: 3

    #include<bits/stdc++.h>
    using namespace std;
    const int MAXN = 1 << 8;
    int k;
    int v[MAXN + 5][MAXN + 5];
    int c;
    // 比赛函数
    int compete(int l, int r) {
          
          
        if (l == r) return l;
        int m = (l + r) / 2;
        int w1 = compete(l, m);
        int w2 = compete(m + 1, r);
    //    cout<<"w1:"<<w1<<" w2:"<<w2<<" v[w1][w2]:"<<v[w1][w2]<<endl; 
    //    cout<<c++<<endl; 
        if(v[w1][w2]==w2) 
        {
          
          
        	return w2;
    	}
    	else
    	{
          
          
    		return w1;
    	}
    }
    
    int main() {
          
          
        cin >> k;
    //    cout<<(1<<k)<<endl;  // 注意左移1位的话 ->*2 
        for (int i = 1; i <= 1<<k; i++) {
          
          
            for (int j = 1; j <= 1<<k; j++) {
          
          
                cin >> v[i][j];
            }
        }
        cout << compete(1, 1<<k) << endl;
        return 0;
    }
    

Guess you like

Origin blog.csdn.net/daxuanzi515/article/details/130319412