hdu 2590 Building roads(环+贪心)

42 篇文章 0 订阅
4 篇文章 0 订阅

Building roads

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 121    Accepted Submission(s): 13


Problem Description
There is a circle-shape lake in a beautiful town. And along the lake, there are N cities, living lots of pigs. 
In 2008, the number of pigs is growing so faster that the government decide to transfer some pigs from some cities to others. And they want to make that each city has the same number of pigs.
Before the transfer, the government has to build some roads between cities. For example, if we want to move some pigs from city A to city B, we have to build a road between A and B. Now the government wants to save more money for the National's Day, so they want to build roads as few as possible, i.e, they want to know how many roads at least they have to build to make that each city has the same number of pigs.



Giving the initial number of pigs of each city, you should tell me the least number of roads have to build. If it is impossible to make each city has the same number of pigs, output "Impossible".
 

Input
There will be multiple input sets. The first line of input will contain a integer K, means the number of sets.
Input for each set is a positive integer n(means the number of cities, 1 <= n <= 10000) on a line by itself, followed one line containing some positive integers(no more than 10000), indicate the cities' initial number of pigs.
 

Output
Output for each input set should be one line containing a positive integer R, means the least number of roads have to build, output "Impossible" if it is impossible to make each city has the same number of pigs
 

Sample Input
  
  
4 3 1 2 3 3 2 2 2 4 1 3 1 3 3 1 3 3
 

Sample Output
  
  
1 0 2 Impossible

solution:

若平均值为整数,那么我们把每个值都减去平均值,这样一圈的和为0,很显然,最多需要n-1次,如果我们划分出了m个和为零的区间,那么最多需要n-m次。

#include<cstdio>
#include<algorithm>
#include<map>
using namespace std;
const int maxn = 1e4 + 200;
int a[maxn];
int main()
{
    int t, n, x;
    scanf("%d", &t);
    while (t--)
    {
        scanf("%d", &n);
        int ans =1e9;
        long long sum = 0,sum1=0;
        map<long long, int>q;
        for (int i = 0; i < n; i++)
        {
            scanf("%d", &a[i]);
            sum1 += a[i];
        }
        if (sum1%n != 0)
        {
            printf("Impossible\n");
            continue;
        }
        for (int i = 0; i < n; i++)
        {
            a[i] -= sum1 / n;
            sum += a[i];
            q[sum]++;
            ans = min(ans, n - q[sum]);
        }
        printf("%d\n", ans);
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值