PAT 1034. Head of a Gang

题目:http://pat.zju.edu.cn/contests/pat-a-practise/1034

题解:

代码:

#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
#define INF 0x6fffffff
map weight;
map flag;
map out;
map > link;
int idx,allWeight;
string st;
void dfs(string x)
{
    flag[x]=true;
    allWeight+=weight[x];
    if(weight[x]>weight[st])//如果当前的权重大于头,则替换头
        st=x;
    for(vector::iterator it=link[x].begin();it!=link[x].end();++it)
    {//遍历相连的结点
        if(flag[*it]==false)//判断是否访问过
            dfs(*it);
    }
    ++idx;
}
int main()
{
    int n,k;
    int w;
    char a[5],b[5];
    string aName,bName;
    scanf("%d%d",&n,&k);
    for(int i=0;isecond+=w;
        if(weight.find(bName)==weight.end())
            weight.insert(make_pair(bName,w));
        else
            weight.find(bName)->second+=w;
        link[aName].push_back(bName);
        link[bName].push_back(aName);
        flag[aName]=false;
        flag[bName]=false;
    }
    for(map::iterator it=flag.begin();it!=flag.end();++it)
    {
        if(it->second==false)
        {
            idx=0;
            allWeight=0;
            st=it->first;
            dfs(st);
            if(idx>2&&allWeight/2>k)
                out[st]=idx;
        }
    }
    printf("%d\n",out.size());
    for(map::iterator it=out.begin();it!=out.end();++it)
        printf("%s %d\n",it->first.c_str(),it->second);
    return 0;
}

来源: http://blog.csdn.net/acm_ted/article/details/20789637



你可能感兴趣的:(PAT)