题意:
n个车牌号,刚开始只有一个车牌,其他车牌都是由一个车牌直接或间接产生,一个车牌到另一个车牌的产生权值是它们之间的数字不同的个数,问产生的最小的边权和,即求最小生成树
。
Input:
多组数据。第一行一个数字n,车牌数量,接下来n行为车牌序列。输入0结束。
Output:
每组数据输出一行
“The highest possible quality is 1/Q”。Q是最佳推导计划的质量
思路:
把给出的车牌序列,想象成一个二维数组。要得到edge边里的权重,就需要获得车牌间两两转换的权重。所以使用两重循环来计算两两间的权重。而,权重即为两个7个字母的车牌序列之间 不一样的字母个数
Kruskal
#pragma warning(disable:4996)
#include<iostream>
#include<string>
#include<cmath>
#include<ctype.h>
#include<memory.h>
#include<string.h>
#include<algorithm>
#include<map>
#include<iomanip>
#include<set>
#include<list>
#include<vector>
#include<stack>
#include<queue>
using namespace std;
const int maxn = 2010;
struct edge
{
int u, v, w;
};
bool cmp(edge a, edge b)
{
return a.w < b.w;
}
int n;
int par[maxn];
edge a[maxn * maxn / 2];
int cnt = 0;
int ans = 0;
int find(int x)
{
if (par[x] == x)
return par[x];
return par[x] = find(par[x]);
}
void initilize()
{
cnt = 0;
ans = 0;
for (int i = 0; i <= n; i++)
par[i] = i;
}
int main()
{
while (cin >> n)
{
if (n == 0)
break;
initilize();
string str[maxn];
for (int i = 0; i < n; i++)
cin >> str[i];
for (int i = 0; i <= n - 1; i++)
{
for (int j = n - 1; j >= i; j--)
{
int get_weight = 0;
for (int k = 0; k < 7; k++)
{
if (str[i][k] != str[j][k])
get_weight++;
}
a[cnt].u = i;
a[cnt].v = j;
a[cnt].w = get_weight;
cnt++;
}
}
sort(a, a + cnt, cmp);
for (int i = 0; i < cnt; i++)
{
int x = find(a[i].u);
int y = find(a[i].v);
if (x != y)
{
par[y] = x;
ans += a[i].w;
}
}
cout << "The highest possible quality is 1/" << ans << "." << endl;
}
return 0;
}
Prim:
#pragma warning(disable:4996)
#include<iostream>
#include<string>
#include<cmath>
#include<ctype.h>
#include<memory.h>
#include<string.h>
#include<algorithm>
#include<map>
#include<iomanip>
#include<set>
#include<list>
#include<vector>
#include<stack>
#include<queue>
#define ll long long int
using namespace std;
const int INF = 0x3f3f3f3f;
const int maxn = 2010;
int n;
int Map[maxn][maxn];
int dis[maxn];
int vis[maxn];
int prim(int s)
{
int ans = 0;
memset(vis, 0, sizeof(vis));
for (int i = 1; i <= n; i++)
dis[i] = Map[i][s];
for (int i = 1; i <= n; i++)
{
int Min = INF;
int min_index = -1;
for (int j = 1; j <= n; j++)
{
if (dis[j] < Min && !vis[j])
{
Min = dis[j];
min_index = j;
}
}
if (min_index != -1)
vis[min_index] = 1;
ans += Min;
for (int j = 1; j <= n; j++)
if (dis[j] > Map[j][min_index])
dis[j] = Map[j][min_index];
}
return ans;
}
int main()
{
while (cin >> n)
{
if (n == 0)break;
string str[maxn];
for (int i = 1; i <= n; i++)
cin >> str[i];
for (int i = 1; i <= n; i++)
{
for (int j = n; j >= i; j--)
{
int get_weight = 0;
for (int k = 0; k < 7; k++)
if (str[i][k] != str[j][k])
get_weight++;
Map[i][j] = Map[j][i] = get_weight;
}
}
int ans = prim(1);
cout << "The highest possible quality is 1/" << ans << "." << endl;
}
return 0;
}