L2-017 人以群分 - java

题目解析

给定n个人的活跃度,然后你去求出高活跃人群与低活跃人群,以及两种人群差最大是多少 (人群数要接近)

解题思路

贪心

将活跃度排序,最低的一半人一堆,其他的都是高活跃度的,算出人就好了

注: 这题我java过不了 (超时)

代码

import java.io.*;
import java.math.*;
import java.util.*;

public class Main
{

	public static void main(String[] args) throws IOException
	{
		int n = sc.nextInt();
		int shu[] = new int[n + 10];
		int ans = 0; // 存所有人的活跃度
		for (int i = 1; i <= n; i++)
		{
			shu[i] = sc.nextInt();
			ans += shu[i];
		}

		Arrays.sort(shu, 1, n + 1);

		int m = n / 2;
		for (int i = 1; i <= n / 2; i++)
			ans -= shu[i] + shu[i]; 
//			总活跃度减去两倍低活跃度的
//				减去一个是算高活跃度
//				减去两个是算高活跃与低活跃的差值

		out.printf("Outgoing #: %d\n", (n + 1) / 2);
		out.printf("Introverted #: %d\n", m);
		out.printf("Diff = %d\n", ans);

		out.flush();
		out.close();

	}

	static Scanner sc = new Scanner(System.in);
	static PrintWriter out = new PrintWriter(System.out);

}

c++

#include <iostream>
#include <algorithm>
#include <cmath>

using namespace std;

const int N = 1e5;
int shu[N + 10];

int main()
{
    int n; scanf("%d", &n);
    int ans = 0;
    for(int i = 1; i <= n; i ++)
    {
        scanf("%d", &shu[i]);
        ans += shu[i];
    }
    sort(shu + 1, shu + n + 1);
    
    int m = n / 2;
    for(int i = 1; i <= m; i ++)
        ans -= shu[i] + shu[i];
    
    printf("Outgoing #: %d\n", (n + 1) / 2);
    printf("Introverted #: %d\n", m);
    printf("Diff = %d\n", ans);
    
    return 0;
}

sort

贪心


团体程序设计天梯赛-练习集-java

赞赏