首页 > 代码库 > UVA 10142 Australian Voting(模拟)

UVA 10142 Australian Voting(模拟)

题意:澳大利亚投票系统要求选民们将所有候选人按愿意选择的程度排序,一张选票就是一个排序。一开始,每张选票的首选项将被统计。若有候选人得票超过50%,他讲直接胜出;否则,所有并列最低的候选人出局,而那些将出局候选人排在第一位的选票将被重新统计为排名最高的未出局候选人。这一筛选过程将持续进行,直到某个候选人得到超过50%的选票,或所有候选人得票相同。

#include<cstdio>
#include<cstring>
#include<iostream>
#include<cmath>
#include<algorithm>
using namespace std;
const int N = 50;
#define INF 0x3fffffff
int vote[1050][N];
int out[N], cnt[N];
char name[N][100];
int num;
int main()
{
    int T, n, i, j;
    char str[1000];
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d",&n);
        getchar();
        for(i = 1; i <= n; i++)
            gets(name[i]);
        num = 0;
        while(gets(str) != NULL)
        {
            if(!strcmp(str, "")) break;
            int len = strlen(str);
            int s = 0, k = 0;
            for(i = 0; i < len; i++)
            {
                if(str[i] >= '0' && str[i] <= '9')
                    s = s * 10 + str[i] - '0';
                else
                {
                    vote[num][k++] = s;
                    s = 0;
                }
            }
            vote[num][k++] = s;
            num++;
        }
        memset(out, 0, sizeof(out));
        int flag = 0, rest = n, total = 0;
        while(rest > 1) //未出局候选人数超过1
        {
            total = 0; //总票数
            memset(cnt, 0, sizeof(cnt));
            for(i = 0; i < num; i++)
            {
                for(j = 0; j < n; j++)
                {
                    if(!out[vote[i][j]])
                    {
                        cnt[vote[i][j]]++;
                        total++;
                        break;
                    }
                }
            }
            for(i = 1; i <= n; i++)
                if(cnt[i] * 2 > total && !out[i])
                {
                    printf("%s\n",name[i]);
                    flag = 1;
                    break;
                }
            if(flag) break;
            int mmin = INF, mmax = 0;
            for(i = 1; i <= n; i++)
            {
                if(!out[i])
                {
                    mmin = min(mmin, cnt[i]);
                    mmax = max(mmax, cnt[i]);
                }
            }
            if(mmin == mmax)
                break;
            for(i = 1; i <= n; i++)
                if(cnt[i] == mmin)
                {
                    out[i] = 1;
                    rest--;
                }
        }
        if(!flag)
        {
            for(i = 1; i <= n; i++)
                if(!out[i])
                    printf("%s\n", name[i]);
        }
        if(T > 0)
            printf("\n");
    }
    return 0;
}