天天寫演算法之Virtual Friends
阿新 • • 發佈:2019-02-17
這個題想法很簡單,但是我就是過不去,在map那,要是有人能幫忙找出來,感激不盡
正確程式碼:#include <iostream> #include <cstdio> #include <string> #include <cstring> #include <algorithm> #include <map> #define repf(i,from ,to) for(int i =from;i<=to;i++) #define MAX 111111 using namespace std; int pre[MAX],ncount,nums[MAX]; map<string,int> s; void init( ) { repf(i,1,MAX) { pre[i]=i; nums[i]=1; } s.clear(); ncount= 1 ; } int Find(int x ) { if(pre[x]!=x) { pre[x]=Find(pre[x]); } return pre[x]; } //轉移操作,將a龍珠所在城市的全部龍珠移動到b龍珠所在的城市 void Merge(int a ,int b ) { cout <<"come "<<endl; int fa = Find(a); int fb = Find(b); //直接將a龍珠的祖先fa的父親設定為fb if(fa!=fb) { pre[fa]= fb; nums[fb]+=nums[fa]; } } int T ,F; string a ,b ; int main(){ while(~scanf("%d",&T)) { while(T--) { init(); scanf("%d",&F); while(F--) { scanf("%s%s",&a,&b); if(s[a]==0) { cout << "2"<<endl; s[a]=ncount++; } //這裡會直接炸掉 if(s[b]==0) { cout << "3"<<endl; s[b]=ncount++; } Merge(s[a],s[b]); printf("%d\n",nums[Find(s[a])]); } } } return 0 ; }
#include <iostream> #include <cstdio> #include <string> #include <cstring> #include <algorithm> #include <map> using namespace std; const int maxn=100000+5; int par[maxn],num[maxn];//用來記錄在同一條樹上同類型的個數 char a[25],b[25]; map<string,int>s; int T,F,ncount; void init() { for(int i=0; i<maxn; i++) { par[i]=i; num[i]=1; } s.clear(); ncount=1; } int find(int x) { return par[x]==x?x:par[x]=find(par[x]); } void unite(int x,int y) { x=find(x); y=find(y); if(x==y)return; par[x]=y; num[y]+=num[x]; } int main() { while(~scanf("%d",&T)) { while(T--) { init(); scanf("%d",&F); while(F--) { scanf("%s%s",&a,&b); /**************通過map可以將字串以及一些特殊的結構與數字關聯,起到雜湊函式的作用(更加簡潔)**********************/ if(s[a]==0)s[a]=ncount++; if(s[b]==0)s[b]=ncount++; /************************************/ unite(s[a],s[b]); printf("%d\n",num[find(s[a])]); } } } return 0; }