Truck History POJ - 1789 (为什么prim算法用优先队列这题会Runtime error ,求教,急(一直没想同))

Neiloz 2017-11-18 09:33:45


题意:给出n个长度为7的字符串,每个字符串代表一个车,定义车的距离是两个字符串间不同字母的个数,题目要求的数不同的车的距离的最小值,即所求的就是最小生成树

思路:普通的prim算法可以过,优先队列优化的就过不了。
为什么啊,求教!!!
prim_less 代表普通的prim算法,prim是用队列优化过的(图示用前向星存储的)。
我的算法:

#include <iostream>
#include <string>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <queue>
#include <map>
#include <cstring>
#include <cmath>
#include <set>
#include <map>
using namespace std;
const int maxn=1e6+5;
const int INF=0x3f3f3f3f;
typedef pair<int,int>pp;
int Map[2001][2001];
bool vis[maxn];
int dist[maxn];
int head[3*maxn];
int cnt ;
struct node
{
int data,to,next;
}e[maxn];
void add(int x,int y,int z)//前向星存图
{
e[cnt].to=y;
e[cnt].data=z;
e[cnt].next=head[x];
head[x]=cnt++;
}
int n,m;
char s[2005][8];
int get_distance(int a,int b)//求两点之间的距离
{
int ans =0;
for (int i=0;i<7;i++)
{
if(s[a][i]!=s[b][i])
ans++;
}
return ans;
}

void prim(int st)//优先队列优化,但是挂了
{
int i,j,k;
fill(vis,vis+maxn,0);
fill(dist,dist+maxn,INF);
priority_queue<pp,vector<pp>,greater<pp> >q;
dist[st]=0;
q.push(pp(0,st));
int ans =0;
while (!q.empty())
{
pp p=q.top();
int u=p.second;
if(vis[u])
continue;
ans+=dist[u];
vis[u]=1;
q.pop();
for (i=head[u];i!=-1;i=e[i].next)
{
node w=e[i];
if(dist[w.to]>w.data)
{
dist[w.to]=w.data;
q.push(pp(w.data,w.to));
}
}
}
cout<<"The highest possible quality is 1/"<<ans<<".\n";
}
void prim_less(int st)//普通算法
{
fill(dist,dist+maxn,INF);
fill(vis,vis+maxn,0);
int i,j,k;
dist[st]=0;
// vis[st]=1;
// for (i=0;i<n;i++)
// dist[i]=Map[st][i];
int ans =0;
while (1)
{
int minn=INF;
int u=-1;
for (i=0;i<n;i++)
{
if(minn>dist[i]&&!vis[i])
{
minn=dist[i];
u=i;
}
}
if(u==-1)
break;
vis[u]=1;
ans+=dist[u];
for (i=0;i<n;i++)
dist[i]=min(dist[i],Map[u][i]);
}
cout<<"The highest possible quality is 1/"<<ans<<".\n";
}

int main()
{
// std::ios::sync_with_stdio(0);
// cin.tie(0);
int x,y,z;
int i,j,k;
while (~scanf("%d",&n))
{
if(!n)
break;
cnt=0;
fill(head,head+maxn,-1);
for (i=0;i<n;i++)
scanf("%s",s[i]);
for (i=0;i<n;i++)
for (j=i+1;j<n;j++)
{
int temp=get_distance(i,j);
add(i,j,temp);
add(j,i,temp);
// Map[i][j]=Map[j][i]=temp;//prim_less
}
prim(0);
// prim_less(0);
}
return 0;
}


...全文
127 1 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
__Simon_ 2019-02-17
  • 打赏
  • 举报
回复
跟优先级队列无关,你数组开小了吧。需要n*n条边吧。
但是这题用前向星爆内存,得用邻接矩阵+优先级队列

65,186

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧