[PAT解题报告] Head of a Gang

题目给了个很好的背景,就是人物之间打电话。人可以看作节点,边可以看作通话时间,图是无向的。定义一个连通分量可能就是一个团伙,还需要看
(1) 连通分量里的节点数 大于1
(2) 边总权值大于一个阈值K
这个都很简单,我们对于每个点,求连通分量,顺便打上标号(我写的where)就表示它在哪个分量里,按照联通分量标号排序,同一个连通分量的点在一起。求连通分量可以用dfs,顺便求出每个点连边权的总和,也能求出分量里所有边权值和——别忘记除以2和K比较。这样就能找到团伙。排序时同一个团伙把连边权和大的节点放在前面,就能找到每个团伙的头。
还要注意字符串到整数id之间使用map直接映射就好了。

代码:
#include <cstdio>
#include <cstring>
#include <string>
#include <map>
#include <set>
#include <algorithm>
using namespace std;
struct node {
char name[4];
int where;
int weight;
};
map<string,int> id;
int a[2048][2048];
node p[2048];
char s[10];
int n;
set<pair<string,int> > all;
bool cmp(const node &a, const node &b) {
    return (a.where < b.where) || ((a.where == b.where) && (a.weight > b.weight));
}
int give(char *name) {
map<string,int>::iterator t = id.find(name);
    if (t == id.end()) {
        int r = id.size();
        strcpy(p[r].name, name);
        p[r].weight = 0;
        p[r].where = -1;
        return id[name] = r;
    }
    return t->second;
}
void dfs(int x, int y) {
    if (p[x].where >= 0) {
        return;
    }
    p[x].where = y;
    for (int i = 0; i < n; ++i) {
        if (a[x][i]) {
            p[x].weight += a[x][i];
            dfs(i, y);
        }
    }
}
int main() {
int k;
    scanf("%d%d",&n,&k);
    for (int i = 0; i < n; ++i) {
        scanf("%s",s);    
        int x = give(s), len;    
        scanf("%s%d",s,&len);
        int y = give(s);
        a[x][y] += len;
        a[y][x] += len;
    }
    n = id.size();
    for (int i = 0; i < n; ++i) {
        dfs(i, i);
    }
    sort(p, p + n, cmp);
    for (int i = 0; i < n; ) {
        int total = 0, j;
        for (j = i; (i < n) && (p[j].where == p[i].where); total += p[i++].weight)
        ;
        if ((i - j > 2) && ((total >> 1) > k)) {
            all.insert(make_pair((string) p[j].name, i - j));
        }
    }
    printf("%d\n",all.size());
    for (set<pair<string,int> >::iterator t = all.begin(); t != all.end(); ++t) {
        printf("%s %d\n",t->first.c_str(), t->second);
    }
    return 0;
}

原题链接: http://www.patest.cn/contests/pat-a-practise/1034
全部评论
PAT无法通过
点赞 回复 分享
发布于 2020-11-19 17:13
大牛,你好,题目难道不是要求在一个gang 里面每两个人都应该有通话吗?难道可以间接?
点赞 回复 分享
发布于 2015-08-22 23:28

相关推荐

头像
今天 20:19
已编辑
门头沟学院 人工智能
本文略长,献给身处双非、学院本科的低年级依旧陷入迷茫的同学,一个参考。夹杂强烈主观因素,若观点不同,仅当笑料。近日,工作之余的午休时间给母校的学弟学妹进行了宣讲,同时也接受了牛客的访谈,不约而同的触发了两个关键词考研,就业。现象今年和去年,认识的学弟学妹,来自知某、抖某、牛客等系列的学弟学妹,这次宣讲,约有20个学弟学妹来加了我的联系方式,向我取经,聊聊未来,聊聊想法。我这里简单概括一下。1.现在很迷茫,大方向摇摆就业还是考研,但是倾向考研。小方向摇摆竞赛和项目,不知道怎么去做,不知道怎么开始。2.考研的直接目的绝大多数都是为了(混)学历,根本目的就是提高就业竞争力。3.我把他们都拉了个群,在...
牛客85294058...:“私聊能够滔滔不绝,而拉了一个小群之后就完全一声不吭”个人观点这跟从小到大“不要浪费大家时间”的社会环境有关:个人化的提问,如果你上学时有留心、或者参加QA环节多,会注意到这种做法经常是被人骂的。要营造让大家开口的氛围和做出欢迎讨论的议题设置还是比较难的,期待方法探索。
投递大连飞创信息技术有限公司等公司10个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务