PAT (Advanced Level) 1034. Head of a Gang (30)

简单DFS。

#include<cstdio>
#include<cstring>
#include<cmath>
#include<vector>
#include<map>
#include<string>
#include<queue>
#include<stack>
#include<algorithm>
#include<iostream>
using namespace std;

const int maxn=2000+10;
map<string,int>m1;
map<int,string>m2;
int n,k,tot;

struct Edge
{
    int u,v,val;
}e[maxn];

struct Ans
{
    string name;
    int cnt;
}ans[maxn];
int num;

vector<int>g[maxn];
int flag[maxn];
int Block;
int cnt[maxn];

void dfs(int x)
{
    num++; flag[x]=Block;
    for(int i=0;i<g[x].size();i++)
    {
        if(flag[g[x][i]]!=0) continue;
        dfs(g[x][i]);
    }
}

bool cmp(const Ans&a,const Ans&b){return a.name<b.name;}

int main()
{
    scanf("%d%d",&n,&k); tot=0;
    memset(flag,0,sizeof flag);
    memset(cnt,0,sizeof cnt);
    for(int i=1;i<=n;i++)
    {
        string a,b; cin>>a>>b>>e[i].val;
        if(m1[a]==0)
        {
            m1[a]=++tot;
            m2[tot]=a;
        }
        if(m1[b]==0)
        {
            m1[b]=++tot;
            m2[tot]=b;
        }
        e[i].u=m1[a];
        e[i].v=m1[b];
        cnt[e[i].v]+=e[i].val;
        cnt[e[i].u]+=e[i].val;
        g[e[i].u].push_back(e[i].v);
        g[e[i].v].push_back(e[i].u);
    }

    num=0;
    int t=0;
    for(int i=1;i<=tot;i++)
    {
        if(flag[i]!=0) continue;
        Block++; num=0; dfs(i);
        if(num<=2) continue;
        int sum=0;
        for(int j=1;j<=n;j++)
            if(flag[e[j].u]==Block&&flag[e[j].v]==Block)
                sum=sum+e[j].val;
        if(sum<=k) continue;

        int id,Max=-1;
        for(int j=1;j<=tot;j++)
            if(flag[j]==Block&&cnt[j]>Max)
                Max=cnt[j],id=j;

        ans[t].name=m2[id];
        ans[t].cnt=num;
        t++;
    }

    sort(ans,ans+t,cmp);

    printf("%d\n",t);
    for(int i=0;i<t;i++)
        cout<<ans[i].name<<" "<<ans[i].cnt<<endl;

    return 0;
}

 

posted @ 2016-05-21 22:11  Fighting_Heart  阅读(128)  评论(0编辑  收藏  举报