您的位置:首页 > 其它

Hoj 1961 Arctic Network/Hoj 2507 The Bug Sensor Problem

2013-08-22 09:46 302 查看
两道求最小生成树第K大(小)边的题目。

一般这种题目都是一个原本的连通图分割成s个连通分量,求这些连通分量中最长边。那么这就是求原图中最小生成树

中第s大的边的长度。因为连接这s个连通分量的边肯定要求是前s-1长的边,这些边有s-1个。

第一题:Hoj 1961 Arctic Network

题目链接:http://acm.hit.edu.cn/hoj/problem/view?id=1961

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <stack>
#include <queue>
#include <algorithm>
#include <iostream>

using namespace std;

#define Maxn 505
struct Point
{
int x,y;
}point[Maxn];

double graph[Maxn][Maxn];
double dist[Maxn];
int vis[Maxn];
int s,p;
int m;
double ans[Maxn];

double getDis(Point a,Point b)
{
return sqrt((double)(a.x - b.x)*(a.x - b.x) + (double)(a.y - b.y)*(a.y - b.y));
}
void prim()
{
dist[0] = 0;
for(int i=1;i<p;i++)
{
dist[i] = 100000000;
}
memset(vis,0,sizeof(vis));
m = 0;
for(int i=0;i<p;i++)
{
double mi = 100000000;
int mik;
for(int j=0;j<p;j++)
{
if(dist[j]<mi && !vis[j]) mi = dist[j],mik = j;
}
ans[m++] = mi;
vis[mik] = 1;
for(int j=0;j<p;j++)
{
if(dist[j]> graph[mik][j]) dist[j] = graph[mik][j];
}
}
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("in.txt","r",stdin);
#endif
int t;

scanf(" %d",&t);
while(t--)
{
scanf(" %d %d",&s,&p);
for(int i=0;i<p;i++)
{
scanf(" %d %d",&point[i].x,&point[i].y);
}
for(int i=0;i<p;i++)
{
graph[i][i] = 0;
for(int j=i+1;j<p;j++)
{
graph[i][j] = graph[j][i] = getDis(point[i],point[j]);
}
}
prim();
sort(ans+1,ans+m);
printf("%.2f\n",ans[p-s]);
}
return 0;
}


第二题:Hoj 2507 The Bug Sensor Problem

题目链接:http://acm.hit.edu.cn/hoj/problem/view?id=2507

此题与上题稍有不同,如果数据范围太大的话,double graph[Maxn][Maxn]太大。

那么我们事先可以不预处理graph,可以在松弛过程中再去比对。

这样就可以节省空间。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <stack>
#include <queue>
#include <algorithm>
#include <iostream>

using namespace std;

#define Maxn 100005
#define INF 0x3f3f3f3f

struct Point
{
double x,y;
}point[Maxn];

double dist[Maxn];
int vis[Maxn];
int s,p;
int m;
double ans[Maxn];

double getDis(Point a,Point b)
{
return sqrt((double)(a.x - b.x)*(a.x - b.x) + (double)(a.y - b.y)*(a.y - b.y));
}
void prim()
{
dist[0] = 0;
for(int i=1;i<p;i++)
{
dist[i] = INF;
}
memset(vis,0,sizeof(vis));
m = 0;
for(int i=0;i<p;i++)
{
double mi = INF;
int mik;
for(int j=0;j<p;j++)
{
if(dist[j]<mi && !vis[j]) mi = dist[j],mik = j;
}
ans[m++] = mi;
vis[mik] = 1;
for(int j=0;j<p;j++)
{
if(dist[j]> getDis(point[mik],point[j])) dist[j] = getDis(point[mik],point[j]);
}
}
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("in.txt","r",stdin);
#endif
int w;
double a,b;
scanf("  %d",&w);
while(w--)
{
p = 0;
scanf(" %d",&s);
while(scanf(" %lf",&a)!=EOF && a!=-1)
{
scanf(" %lf",&b);
point[p].x = a,point[p].y = b;
p++;
}
prim();
sort(ans+1,ans+m);
printf("%.0f\n",ceil(ans[p-s]));
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: