Prim求调,WA on #3#4
查看原帖
Prim求调,WA on #3#4
1057966
youlunkubiaoke楼主2024/8/24 14:32

代码如下

//#pragma GCC optimize(3)
#include<iostream>
#include<vector>
#include<queue>
#include<climits>
using namespace std;
typedef unsigned long long int UL;
typedef long long int LL;
typedef unsigned short US;
typedef double DB;
struct Edge
{
    LL to;
    LL cost;
};
class CMP
{
    public:
        bool operator()(Edge edge1,Edge edge2)
        {
            if (edge1.cost>edge2.cost)
              return true;
            return false;
        }
};
LL n,m,sum=0,mst[5002]={0};
bool visited[5002]={false};
vector<Edge> g[5002],ans;
priority_queue<Edge,vector<Edge>,CMP> pq;
Edge make_edge(LL to,LL cost)
{
    Edge edge;
    edge.to=to;
    edge.cost=cost;
    return edge;
}
int main()
{
    ios::sync_with_stdio(false);
    LL u,v,w;
    cin>>n>>m;
    for (LL m1=1;m1<=m;m1++)
    {
        cin>>u>>v>>w;
        g[u].push_back(make_edge(v,w));
        g[v].push_back(make_edge(u,w));
    }
    for (LL n1=1;n1<=n;n1++)
    {
        mst[n1]=LLONG_MAX;
    }
    mst[1]=0;
    visited[1]=1;
    for (LL i=0;i<g[1].size();i++)
    {
        Edge e=g[1][i];
        mst[e.to]=e.cost;
        pq.push(e);
    }
    while (pq.empty()!=true)
    {
        Edge top=pq.top();
        pq.pop();
        if (ans.size()==n-1)
          break;
        if (visited[top.to]!=true)
          ans.push_back(top);
        else
          continue;
        visited[top.to]=true;
        for (LL i=0;i<g[top.to].size();i++)
        {
            Edge e=g[top.to][i];
            if (visited[e.to]!=true&&mst[e.to]>e.cost)
            {
                mst[e.to]=e.cost;
                pq.push(e);
            }
        }
    }
    for (LL n1=1;n1<=n;n1++)
    {
        if (mst[n1]>LLONG_MAX-1)
        {
            cout<<"orz"<<endl;
            return 0;
        }
        sum+=mst[n1];
    }
    cout<<sum<<endl;
    return 0;
}
2024/8/24 14:32
加载中...