POJ 1258 Agri-net

#include 
#include 
#include 
#include 
#include 
using namespace std;
#define MAXN 105
#define INF 0xffffff
class Graph
{
	private:
		int V[MAXN];
		int v;
		int e;
		int g[MAXN][MAXN];
	public:
		Graph()
		{
			for(int i = 1; i <= MAXN; i++)
			{
				V[i] = 0;
				for(int j = 1; j <= MAXN; j++)
				{
					g[i][j] = INF;
				}
			}
			v = 0;
			e = 0;
		}
		Graph(int n)
		{
			for(int i = 1; i <= n; i++)
			{
				V[i] = 0;
				for(int j = 1; j <= n; j++)
				{
					g[i][j] = INF;
				}
			}
			v = 0;
			e = 0;
		}
		int getV()
		{
			return v;
		}
		int getE()
		{
			return e;
		}
		int getW(int i, int j)
		{
			return g[i][j];
		}
		void insert(int a, int b)
		{
			g[a][b] = 1;
			e++;
			if(!V[a])
			{
				V[a]++;
				v++;
			}
			if(!V[b])
			{
				V[b]++;
				v++;
			}
		}
		void insert(int a, int b, int w)
		{
			g[a][b] = w;
			e++;
			if(!V[a])
			{
				V[a]++;
				v++;
			}
			if(!V[b])
			{
				V[b]++;
				v++;
			}
		}
		void del(int a, int b)
		{
			g[a][b] = INF;
			e--;
			e++;
			V[a]--;
			V[b]--;
			if(!V[a])
			{
				v--;
			}
			if(!V[b])
			{
				v--;
			}
		}
};
class Mst
{
	private:
		int v;
		int e;
		int maxw;
		int sumw;
		int father[MAXN];
		int distance[MAXN];
		bool visit[MAXN];
	public:
		Graph g;
		Mst()
		{
			v = 0;
			e = 0;
			maxw = 0;
			sumw = 0;
			memset(visit, false, sizeof(visit));
			memset(father, -1, sizeof(father));
		}
		int getMaxW()
		{
			return maxw;
		}
		int getSumW()
		{
			return sumw;
		}
		void primBuild()
		{
			visit[1] = true;
			v++;
			for(int i = 1; i <= g.getV(); i++)
			{
				distance[i] = g.getW(0, i);
			}
			int tmpV;
			for(int j = 1; j <= g.getV(); j++)
			{
				int minDis = INF;
				for(int i = 1; i <= g.getV(); i++)
				{
					if(visit[i] == false && distance[i] < minDis)
		            {
		                minDis = distance[i];
		                tmpV = i;
		            }
				}
				visit[tmpV] = true;
				v++;
				e++;
				sumw += minDis;
				if(maxw < minDis)
				{
					maxw = minDis;
				}
            	for(int i = 1; i <= g.getV(); i++)
		        {
		            if(visit[i] == false && distance[i] > g.getW(v, i))
		            {
		                distance[i] = g.getW(v, i);
		            }
		        }
			}
		}
};
int n, w;

int main()
{
	while(scanf("%d", &n) != EOF)
	{
		Mst mst;
		for(int i = 0; i < n; i++)
		{
			for(int j = 0; j < n; j++)
			{
				scanf("%d", &w);
				mst.g.insert(i, j, w);
			}
		}
		mst.primBuild();
		printf("%d\n", mst.getMaxW());	
	}
	return 0;
}

你可能感兴趣的:(ACM)