poj2454 Jersey Politics (随机化算法)

Jersey Politics

In the newest census of Jersey Cows and Holstein Cows, Wisconsin cows have earned three stalls in the Barn of Representatives. The Jersey Cows currently control the state’s redistricting committee. They want to partition the state into three equally sized voting districts such that the Jersey Cows are guaranteed to win elections in at least two of the districts.

Wisconsin has 3K (1 <= K <= 60) cities of 1,000 cows, numbered 1…3K, each with a known number (range: 0…1,000) of Jersey Cows. Find a way to partition the state into three districts, each with K cities, such that the Jersey Cows have the majority percentage in at least two of districts.

All supplied input datasets are solvable.

Input

  • Line 1: A single integer, K

  • Lines 2…3*K+1: One integer per line, the number of cows in each city that are Jersey Cows. Line i+1 contains city i’s cow census.
    Output

  • Lines 1…K: K lines that are the city numbers in district one, one per line

  • Lines K+1…2K: K lines that are the city numbers in district two, one per line

  • Lines 2K+1…3K: K lines that are the city numbers in district three, one per line

Sample Input

2
510
500
500
670
400
310

Sample Output

1
2
3
6
5
4

Hint

Other solutions might be possible. Note that “2 3” would NOT be a district won by the Jerseys, as they would be exactly half of the cows.

思路:

显然要是的两个区域都大于一半,肯定要用票数最大的前2k个
升序排列这3k个数,sum1=前k个数的和,sum2=中间k个数的和
如果不满足条件,则从第一组中随机找一个数,第二组中随机找一个数,两者交换直到满足条件

code:

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int maxm=205;
struct Node{
    int v,id;
}e[maxm];
bool cmp(Node a,Node b){
    return a.v>b.v;
}
int k;
signed main(){
    scanf("%d",&k);
    for(int i=1;i<=k*3;i++){
        scanf("%d",&e[i].v);
        e[i].id=i;
    }
    sort(e+1,e+1+k*3,cmp);
    int sum1=0,sum2=0;
    for(int i=1;i<=k;i++){
        sum1+=e[i].v;
        sum2+=e[i+k].v;
    }
    while(sum1<=500*k||sum2<=500*k){
        int x=rand()%k+1;
        int y=rand()%k+1+k;
        sum1-=e[x].v;
        sum1+=e[y].v;
        sum2-=e[y].v;
        sum2+=e[x].v;
        swap(e[x],e[y]);
    }
    for(int i=1;i<=k*3;i++){
        printf("%d\n",e[i].id);
    }
    return 0;
}
发布了364 篇原创文章 · 获赞 26 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_44178736/article/details/103276100
今日推荐