题目链接:http://poj.org/problem?id=3164
题意是有n个点m条边,然后输入n个点的坐标,然后输入m个u,v表示相连的两个点,权值为两点间距离,边为单向边,问能否将n个点连起来,且花费最少。
其实就是一个有向图的最小生成树,叫做最小树形图,用朱刘算法写,这道题直接套模板就好了,但是tmd有坑点,最后的结果要输出%.2f,不能是%.2lf,就因为这个卡了我一下午+一晚上,让我一直以为是板子哪里有问题...
AC代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
using namespace std;
const int INF = 0x3f3f3f3f;
const int MAXN = 1010;
const int MAXM = 1010*1010;
struct Node{
double x,y;
}p[MAXN];
struct Edge{
int u, v;
double cost;
}edge[MAXM];
int pre[MAXN], id[MAXN], vis[MAXN];
double in[MAXN];
int n,m,root;
double dist(Node a,Node b){
return sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y));
}
double solve()
{
double res = 0;
while (1){
for(int i=0;i<n;i++) in[i] = INF;
for(int i=0;i<m;++i){
int u = edge[i].u, v = edge[i].v;
if(edge[i].cost < in[v] && u != v){
pre[v] = u;
in[v] = edge[i].cost;
}
}
for (int i = 0; i < n; i++){
if (i != root && in[i] == INF) return -1;
}
int tn = 0;
memset(id, -1, sizeof(id));
memset(vis, -1, sizeof(vis));
in[root] = 0;
for(int i = 0; i < n; i++){
res += in[i];
int v = i;
while(vis[v] != i && id[v] == -1 && v != root){
vis[v] = i;
v = pre[v];
}
if(v != root && id[v] == -1)
{
for(int u = pre[v]; u != v ; u = pre[u]) id[u] = tn;
id[v] = tn++;
}
}
if (tn == 0) break;
for (int i = 0; i < n; i++){
if(id[i] == -1) id[i] = tn++;
}
for (int i = 0; i < m; i++){
int v = edge[i].v;
edge[i].u = id[edge[i].u];
edge[i].v = id[edge[i].v];
if (edge[i].u != edge[i].v) edge[i].cost -= in[v];
}
n = tn;
root = id[root];
}
return res;
}
int main()
{
while(~scanf("%d%d",&n,&m)){
for(int i=0;i<n;i++){
scanf("%lf%lf",&p[i].x,&p[i].y);
}
for(int i=0;i<m;i++){
scanf("%d%d",&edge[i].u,&edge[i].v);
edge[i].u --; edge[i].v --;
if(edge[i].u != edge[i].v)
edge[i].cost = dist(p[edge[i].u], p[edge[i].v]);
else edge[i].cost = INF;
}
root = 0;
double ans = solve();
if(ans == -1) printf("poor snoopy\n");
else printf("%.2f\n", ans);
}
return 0;
}