最近在学习c++,为了能够提高和巩固c++程序设计能力,于是在acm做题时,尝试着用c++写代码。下面是我的第一个c++程序,题目来源于acm.pku.cn的2421。望大家多多指教。
1#include<iostream>
2
3using namespace std;
4
5#define INFINITY 1001
6
7
8class prim
9{
10 struct item
11 {
12 int v;
13 int lowedge;
14 }lowcost[100];
15 int r[100][100];
16 int N;
17 int q;
18 public:
19
20 void initialize();
21 int Prim(int v);
22 friend void ReadData();
23
24};
25void prim::initialize()
26{
27
28
29
30 for(int i = 0;i<N;i++)
31 {
32 for(int j=0;j<N;j++)
33 {
34 r[i][j]=INFINITY;
35
36 }
37 }
38}
39int prim::Prim(int v)
40{
41 int min,w=0,result=0;
42 int i,j;
43 for(i=0;i < N;i++)
44 {
45 lowcost[i].lowedge = r[v][i];
46 lowcost[i].v = v;
47 }
48 lowcost[v].lowedge = -1;
49
50 for(i = 1;i<N;i++)
51 {
52 min = INFINITY;
53 for(j = 0;j<N;j++)
54 {
55 if(lowcost[j].lowedge > -1 && lowcost[j].lowedge<min)
56 {
57 min = lowcost[j].lowedge;
58 w = j;
59 }
60 }
61
62 result += lowcost[w].lowedge;
63 lowcost[w].lowedge = -1;
64 for(j = 0;j<N;j++)
65 {
66 if(r[w][j] < lowcost[j].lowedge &&lowcost[j].lowedge >-1)
67 {
68 lowcost[j].lowedge = r[w][j];
69 lowcost[j].v = w;
70 }
71 }
72 }
73 return result;
74
75}
76
77void ReadData()
78{
79 prim s;
80 int x,y;
81 scanf("%d",&s.N);
82 s.initialize();
83 for(int i = 0;i<s.N;i++)
84 {
85 for(int j=0;j<s.N;j++)
86 {
87
88 scanf("%d",&s.r[i][j]);
89
90
91 }
92 }
93 scanf("%d",&s.q);
94 for(i = 0;i<s.q;i++)
95 {
96 scanf("%d%d",&x,&y);
97 s.r[x-1][y-1] = s.r[y-1][x-1] = 0;
98
99 }
100 printf("%d\n",s.Prim(0));
101}
102
103int main()
104{
105
106 ReadData();
107 return 0;
108
109}
2
3using namespace std;
4
5#define INFINITY 1001
6
7
8class prim
9{
10 struct item
11 {
12 int v;
13 int lowedge;
14 }lowcost[100];
15 int r[100][100];
16 int N;
17 int q;
18 public:
19
20 void initialize();
21 int Prim(int v);
22 friend void ReadData();
23
24};
25void prim::initialize()
26{
27
28
29
30 for(int i = 0;i<N;i++)
31 {
32 for(int j=0;j<N;j++)
33 {
34 r[i][j]=INFINITY;
35
36 }
37 }
38}
39int prim::Prim(int v)
40{
41 int min,w=0,result=0;
42 int i,j;
43 for(i=0;i < N;i++)
44 {
45 lowcost[i].lowedge = r[v][i];
46 lowcost[i].v = v;
47 }
48 lowcost[v].lowedge = -1;
49
50 for(i = 1;i<N;i++)
51 {
52 min = INFINITY;
53 for(j = 0;j<N;j++)
54 {
55 if(lowcost[j].lowedge > -1 && lowcost[j].lowedge<min)
56 {
57 min = lowcost[j].lowedge;
58 w = j;
59 }
60 }
61
62 result += lowcost[w].lowedge;
63 lowcost[w].lowedge = -1;
64 for(j = 0;j<N;j++)
65 {
66 if(r[w][j] < lowcost[j].lowedge &&lowcost[j].lowedge >-1)
67 {
68 lowcost[j].lowedge = r[w][j];
69 lowcost[j].v = w;
70 }
71 }
72 }
73 return result;
74
75}
76
77void ReadData()
78{
79 prim s;
80 int x,y;
81 scanf("%d",&s.N);
82 s.initialize();
83 for(int i = 0;i<s.N;i++)
84 {
85 for(int j=0;j<s.N;j++)
86 {
87
88 scanf("%d",&s.r[i][j]);
89
90
91 }
92 }
93 scanf("%d",&s.q);
94 for(i = 0;i<s.q;i++)
95 {
96 scanf("%d%d",&x,&y);
97 s.r[x-1][y-1] = s.r[y-1][x-1] = 0;
98
99 }
100 printf("%d\n",s.Prim(0));
101}
102
103int main()
104{
105
106 ReadData();
107 return 0;
108
109}