Poj1789 truck history minimum spanning tree kruskal

Title Link

               https://cn.vjudge.net/contest/245639#problem/E

The main idea of the topic

At the beginning, I couldn't understand the meaning of the topic. I only understood it below Baidu. It means that the number of different characters in two strings is the distance between the two strings. For example

4
 aaaaaaa ---- No.1
 Baaaaa - No. 2
 abaaaaa - No. 3
 aabaaaa - No. 4

The first character of No. 1 and No. 2 is different, and only one is different, so the distance between No. 1 and No. 2 is 1

The first and second characters of No. 2 and No. 3 are different, and only two are different, so the distance between No. 2 and No. 3 is 2

and so on....

Title Analysis

Using kruskal, it has three elements, e[i].from, e[i].to, e[i].val, where e[i].val refers to the number of different characters in a string

Code example

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cmath>
#include<cstring>
#define N 2000
using namespace std;
const int maxn = N*(N-1)/2+5;

int per[N],n,m,s,res;
char ss[N][10];
struct node{ int from, to, val; }e[maxn];
bool cmp(node a, node b){ return a.val < b.val; }
int find(int x){ return per[x] == x ? x : per[x] = find(per[x]); }
void init()
{
	for (int i = 1; i <= n; i++) per[i] = i;
}
void input()
{
	for (int i = 1; i <= n; i++)
	{
		getchar();
		scanf("%s", ss[i]);
	}
}
void datastand()
{
	m = 0;
	for (int i = 1; i < n; i++)
	for (int j = i+1; j <= n; j++)
	{
		int num = 0;
		for (int k = 0; k <= 6;k++)
		if (ss[i][k] != ss[j][k]) num++;   //Count the number of different characters in two strings
		e[m].from = i;
		e[m].to = j;
		e[m++].val = num;
	}
	/*for (int i = 0; i < m; i++)
		cout << e[i].from << ' ' << e[i].to << ' ' << e[i].val << endl;*/
	sort(e, e + m, cmp);
}
void kruskal()
{
	res = 0;
	for (int i = 0; i < m; i++)
	{
		int fa = find(e[i].from), fb = find(e[i].to);
		if (fa!=fb)
		{
			per[fa] = fb;
			res += e[i].val;
		}
	}
	printf("The highest possible quality is 1/%d.\n", res);
}
int main()
{
	while (cin >> n, n)
	{
		init();
		input();
		datastand();
		kruskal();
	}
	return 0;
}

 

Posted by robsgaming on Fri, 03 Jan 2020 01:54:17 -0800