圖的遍歷 dfs pat 1034

#include <iostream>
//1034,dfs
#include<map>
using namespace std;
const int maxv = 2005;
const int inf = 1e9;
map<string,int> stringToIntl;//姓名到編號
map<string,int> gang;//head到人數
map<int,string> intToString; //編號到姓名
int G[maxv][maxv]={0},weight[maxv] ={0};
bool vis[maxv] ={0};//鄰接矩陣 和點權
int n, k , numPerson = 0;
void dfs(int nowvisit, int& head, int& numMember, int& totalValue){
       vis[nowvisit] = 1;
       numMember++;
       if(weight[nowvisit]>weight[head]){
              head = nowvisit;
       }
       for(int i = 0; i < numPerson; i++){
              if(G[nowvisit][i] != 0){
                     totalValue += G[nowvisit][i];
                     G[nowvisit][i] = G[i][nowvisit] = 0;//防止重複計算
                     if(vis[i]==0){
                            dfs(i,head,numMember,totalValue);
                     }
              }
       }
}

void dfsTrave(){
       for(int i = 0 ; i<numPerson;i++){
              if(vis[i]==0){
                     int head = i,numMember = 0, totalValue = 0;
                     dfs(i,head,numMember,totalValue);
                     if(numMember>2 && totalValue>k){
                            gang[intToString[head]] = numMember;
                     }
              }
       }
}

int change(string s){
       if(stringToIntl.find(s) != stringToIntl.end()){//已經輸入過了,就不用新的編號了
              return stringToIntl[s];
       }else{
              stringToIntl[s] =numPerson;
              intToString[numPerson] =s;
              return numPerson++;//這一行實現return numpetson 並且之後自增1;
       }
}


int main()
{
       freopen("1034.txt","r",stdin);
       int w;
       string s1,s2;
       cin>>n>>k;
       for(int i = 0; i < n;i++){
              cin>>s1>>s2>>w;
              int id1 = change(s1);
              int id2 = change(s2);
              weight[id1] += w;
              weight[id2] += w;
              G[id1][id2] += w;
              G[id2][id1] += w;

       }
       dfsTrave();
       cout<<gang.size()<<endl;
       for(auto it = gang.begin(); it != gang.end();it++){
              cout<<it->first<<" "<<it->second<<endl;
       }
    //cout << "Hello world!" << endl;
    return 0;
}

 

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