標籤:cti cst section 包含 std math amp strong space
題目背景
農民約翰被選為他們鎮的鎮長!他其中一個競選承諾就是在鎮上建立起互連網,並串連到所有的農場。當然,他需要你的協助。
題目描述
約翰已經給他的農場安排了一條高速的網路線路,他想把這條線路共用給其他農場。為了用最小的消費,他想鋪設最短的光纖去串連所有的農場。
你將得到一份各農場之間串連費用的列表,你必須找出能串連所有農場並所用光纖最短的方案。每兩個農場間的距離不會超過100000
輸入輸出格式輸入格式:
第一行: 農場的個數,N(3<=N<=100)。
第二行..結尾: 後來的行包含了一個N*N的矩陣,表示每個農場之間的距離。理論上,他們是N行,每行由N個用空格分隔的數組成,實際上,他們限制在80個字元,因此,某些行會緊接著另一些行。當然,對角線將會是0,因為不會有線路從第i個農場到它本身。
輸出格式:
只有一個輸出,其中包含串連到每個農場的光纖的最小長度。
輸入輸出範例輸入範例#1:
40 4 9 214 0 8 179 8 0 1621 17 16 0
輸出範例#1:
28
說明
題目翻譯來自NOCOW。
USACO Training Section 3.1
60分代碼:(錯誤原因的話是什麼呢?)
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<algorithm> 5 #define Maxn 100001 6 7 using namespace std; 8 9 int n,c=0,f1,f2,tot=0,k=0;10 int f[101];11 12 struct point{13 int x,y,w;14 bool operator < (const point &qwq)const15 {16 return w<qwq.w;17 }//重載運算子(多麼高大上的東西!但我還是不太明白怎麼使用)18 }p[Maxn];19 20 int find(int x)21 {22 if(f[x]!=x) f[x]=find(f[x]);23 return f[x];24 //return x == f[x] ? x : find(f[x]); 25 }26 27 int main()28 {29 int v;30 scanf("%d",&n);31 for(int i=1;i<=n;i++)32 {33 for(int j=1;j<=n;j++)34 {35 scanf("%d",&v);36 if(v!=0) 37 {38 c++;39 p[c].x=i;40 p[c].y=j;41 p[c].w=v;42 }43 }44 }45 for(int i=1;i<=c;i++) f[i]=i;46 sort(p+1,p+c+1);//快排 47 for(int i=1;i<=c;i++)48 {49 f1=find(p[i].x);50 f2=find(p[i].y);51 if(f1!=f2)52 {53 f[f2]=f1;54 tot+=p[i].w;55 k++;56 }57 if(k==n-1) break;58 }59 printf("%d",tot);60 return 0;61 }
AC代碼:(很明顯,我重新寫了,不是用的(!=0)那種方法,用的最基礎的)
1 #include<cstdio> 2 #include<cstdlib> 3 #include<cmath> 4 #include<iostream> 5 #include<algorithm> 6 7 using namespace std; 8 9 int n,Mst;10 int f[101];11 12 struct hh13 {14 int a,b,c;15 bool operator < (const hh &ww)const16 {17 return c < ww.c;18 }19 }d[10001];20 21 int find(int l)22 {23 return l == f[l] ? l : find(f[l]);24 }25 26 int main()27 {28 cin>>n;29 for(int i=1;i<=n;i++)30 for(int j=1;j<=n;j++)31 {32 cin>>d[(i-1)*n+j].c;//進行“超邊處理”,使d能夠“串連”起來 33 d[(i-1)*n+j].a=i;34 d[(i-1)*n+j].b=j;35 } 36 sort(d+1,d+n*n+1);//快排 37 for(int i=1;i<=n;i++)38 f[i]=i;39 int xx=0,i=0;40 while(xx<n-1)41 {42 i++;43 int r1=find(d[i].a);44 int r2=find(d[i].b);45 if(r1!=r2)46 {47 f[r1]=r2;48 xx++;49 Mst+=d[i].c;50 }51 }52 cout<<Mst;53 }
洛穀 P1546 最短網路 Agri-Net x