继续水水题。。。
题目:http://poj.org/problem?id=1789
把车看成结点,车之间的距离看作权重就是一个图了,然后求最小生成树。。。
的确水题,但看题目花了挺长时间,不知道如果现场遇到这种题目会多蛋疼。。。
这题时限2000ms,但用kruscal+sort写出来wa了,换用qsort的话果断超时了,翻了下网上的题解,发现貌似得用const void *传入参数才能快点。
修改完发现又wa了,然后gdb调了一遍,最后发现输出忘了个.。。。无语死。。。
额,后来是sort 1200+ms,qsort 600+ms。。。
贴代码(qsort):
#include <cstdio>
#include <algorithm>
using namespace std;
const int maxn = 2001;
//poj1789
struct Edge{
int x, y, v;
};
struct Edge e[maxn*maxn];
int f[maxn];
void init(int n) {
for (int i = 0; i < n; i++)
f[i] = i;
}
int find(int x) {
if (f[x] != x)
return f[x] = find(f[x]);
return x;
}
int chcmp(const char* a, const char * b) {
int cnt = 0;
for (int i = 0; i < 7; i++)
if (a[i] != b[i])
cnt++;
return cnt;
}
int cmp(const void * a, const void * b){
return (*(struct Edge *)a).v - (*(struct Edge *)b).v;
}
int main() {
int n;
int i, j, cnt, shortest, select;
char str[maxn][7], tmp[7];
// freopen ("in", "r", stdin);
while (scanf("%d", &n) && n) {
init(n);
gets(str[0]);
for (i = 0; i < n; i++)
gets(str[i]);
cnt = 0;
for (i = 0; i < n; i++)
for (j = i + 1; j < n; j++) {
e[cnt].x = i;
e[cnt].y = j;
e[cnt].v = chcmp(str[i], str[j]);
cnt++;
}
qsort(e, cnt, sizeof(e[0]), cmp);
shortest = 0;
select = 0;
for (i = 0; i < cnt; i++) {
int a, b;
a = find(e[i].x);
b = find(e[i].y);
if (a != b){
f[a] = b;
shortest += e[i].v;
if (++select == n - 1)
break;
}
}
printf("The highest possible quality is 1/%d.\n", shortest);
}
return 0;
}
prim