1034 Head of a Gang (30分) PAT

关键要点:

  1. 将字符串作为的key转化为int型的key,此处用的是getnum()函数
  2. 用宽度优先(或深度优先)探索整个图有多少连通分量,其中,人员数目及权重符合的即为gang
  3. 用map存储gang,利用其自动排序的特性。
#include<cstdio>
#include<queue>
#include<vector>
#include<iostream>
#include<map>
#include<string>

using namespace std;

const int maxn = 1010;
const int maxc = 30000;

int getnum(string str) {
    int temp = 0;
    for (int i = 0; i < 3; i++) {
        temp = temp * 26 + str[i] - 'A';
    }
    return temp;
}

int BFS(int a, vector<int> people[], int weight[], bool inq[], int &head, int &pnum) {
    queue<int> q;
    q.push(a);
    inq[a] = true;
    head = a;
    pnum = 0;
    int totalweight = 0;
    while(!q.empty()) {
        int temp = q.front();
        totalweight += weight[temp];
        pnum++;
        q.pop();
        if (weight[head] < weight[temp]) {
            head = temp;
        }
        for (int i = 0; i < people[temp].size(); i++) {
            int temp2 = people[temp][i];
            if (inq[temp2] == false) {
                q.push(temp2);
                inq[temp2] = true;
            }
        }
    }
    return totalweight / 2;
}

void numToChar(string &a, int b) {
    a[0] = b / 26 / 26 + 'A';
    a[1] = (b - (a[0] - 'A') * 26 * 26) / 26 + 'A';
    a[2] = (b - (a[0] - 'A') * 26 * 26 - (a[1] - 'A') * 26) + 'A';
    a[3] = '\0';
}

int main() {
    int N, K;
    string a, b;
    int anum, bnum;
    int tempTime;
    vector<int> people[maxc];
    int weight[maxc] = {0};
    scanf("%d %d", &N, &K);
    vector<int> itv;
    for (int i = 0; i < N; i++) {
        cin >> a >> b >> tempTime;
        // printf("%s %s %d\n", a.c_str(), b.c_str(), tempTime);
        anum = getnum(a);
        bnum = getnum(b);
        weight[anum] += tempTime;
        weight[bnum] += tempTime;
        int j = 0;
        for (j = 0; j < people[anum].size(); j++) {
            if (people[anum][j] == bnum) break;
        }
        if (j == people[anum].size()) {
            people[anum].push_back(bnum);
            people[bnum].push_back(anum);
        }

    }

    bool inq[maxc] = {false};
    queue<int> q;
    map<int, int> gang;
    int totalweight, head, pnum;
    for (int i = 0; i < maxc; i++) {
        if (weight[i] != 0 && inq[i] == false) {
            inq[i] = true;
            totalweight = BFS(i, people, weight, inq, head, pnum);
            if (totalweight > K && pnum > 2) {
                gang[head] = pnum;
            }
        }
    }
    printf("%d\n", gang.size());
    for (map<int, int>::iterator it = gang.begin(); it != gang.end(); it++) {
        numToChar(a, it->first);
        printf("%s %d\n", a.c_str(), it->second);
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值