1034 Head of a Gang (30分) (DFS 圖)

#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <stack>
#include <queue>
#include <map>
using namespace std;
const int maxn = 2010;
int G[maxn][maxn] = {0},weight[maxn] = {0};
map<string,int> stringtoint;
map<int,string> inttostring;
map<string,int> gang;
bool vist[maxn]={0};
int n,k,numperson=0;
int getname(string a) //給每個人編號,字符串轉化爲數字
{
    if(stringtoint.find(a) != stringtoint.end()) //如果沒找到記錄
    {
        return stringtoint[a]; //如果不是第一次,直接輸出編號
    }
    else
    {
        numperson++; //人數++
        stringtoint[a] = numperson; //給與他的編號
        inttostring[numperson] = a;
        return numperson;
    }
}

void DFS(int now,int& head,int& groupper,int& total) //對一個團體DFS,now現在訪問節點,head大哥節點,groupper目前團體人數,total整個團體的邊權
{
    vist[now] = true; //已經訪問
    groupper++;
    if(weight[now] > weight[head]) //點權重更大的是大哥
        head = now;
    for(int i = 1;i<=numperson;i++) //對他的每一個相連的點
    {
        if(G[now][i] > 0) //如果相連
        {
            total += G[now][i];
            G[i][now] = 0; //切斷返回路徑,防止成環的團體重複計算
            G[now][i] = 0;
            if(vist[i] == false)
                DFS(i,head,groupper,total);
        }
    }
}

void DFSTra()
{
    int head,grouper,total=0;
    for(int i = 1;i<=numperson;i++)
    {
        if(vist[i] == false)
        {
            head = i;
            grouper =0;
            total = 0;
            DFS(i,head,grouper,total);
            if(total > k && grouper > 2)
            {
                gang[inttostring[head]] = grouper;
            }
        }

    }
}

int main()
{
    freopen("1.txt","r",stdin);
    scanf("%d %d",&n,&k);
    for(int i = 0;i<n;i++)
    {
        string a,b;
        int a1,b1,time;
//        scanf("%s %s %d",a.c_str(),b.c_str(),&time);
//        printf("%s",a.c_str());
        cin>>a>>b>>time;
        a1 = getname(a);
        b1 = getname(b);
        G[a1][b1] += time;
        G[b1][a1] += time;
        weight[a1] += time;
        weight[b1] += time;
    }
    DFSTra();
    printf("%d\n",gang.size());
    map<string,int>::iterator it;
    for(it = gang.begin();it!=gang.end();it++)
    {
        cout<<it->first<<" "<<it->second<<endl;
    }


    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章