【问题标题】:UVA(769) :critical links getting wrong answerUVA(769):关键链接得到错误答案
【发布时间】:2015-09-12 09:20:57
【问题描述】:

我正在解决 UVA 上的 Critical links 问题。问题是关于在图中找到桥梁。我在这里使用了相同的 algorithm。但我不断得到错误的答案。

请提出我的代码有什么问题。

//Bridges in a Graphs
#include<cstdio>
#include<cstring>
#include<iostream>
#include<vector>
#include<stack>
#include<utility>
#include<cstdlib>
#include<algorithm>
using namespace std;
#define MAX 205
int parent[MAX],timer=0,low[MAX],disc[MAX];
bool vis[MAX];
vector<pair<int,int> >st;
vector<vector<int> >G(MAX);
bool cmp(const pair<int,int> a,pair<int,int> b)
{
    if(a.first==a.second)
    return a.second<b.second;
    else
    return a.first<b.first;
}
void reset()
{
    st.clear();
    memset(parent,-1,sizeof parent);
    memset(vis,false,sizeof vis);
    for(int i=0;i<=MAX;i++)
    G[i].clear();
}
void dfs(int u)
{   
    vis[u]=true;
    disc[u]=low[u]=timer++;
    for(int i=0;i<G[u].size();i++)
    {
        int v=G[u][i];
        if(!vis[v])
        {
            parent[v]=u;
            dfs(v);
            low[u]=min(low[u],low[v]);
            if(low[v]>low[u])
            st.push_back(make_pair(min(u,v),max(u,v)));
        }
        else if(v!=parent[u])
            low[u]=min(low[u],disc[v]);
    }
}
int main()
{
    int n,t=0;

    while(cin>>n)
    {
        reset();
        if(t>0)
        cout<<endl;
        if(n==0)
        {
            cout<<"0"<<" critical links\n";break;
        }
        int node,count;

        for(int j=0;j<n;j++)
        {
            scanf("%d (%d)",&node,&count);
            for(int i=0;i<count;i++)
            {
                int x;
                scanf("%d",&x);
                G[node].push_back(x);
                G[x].push_back(node);
            }
        }
        for(int i=0;i<n;i++)
        {
            if(!vis[i])
            dfs(i);
        }
        sort(st.begin(),st.end(),cmp);
        cout<<st.size()<<" critical links\n";

        for(int i=0;i<st.size();i++)
        cout<<st[i].first<<" - "<<st[i].second<<endl;
        t++;

    }
}

【问题讨论】:

  • 将 C I/O(scanf 等)与 C++ I/O(cin &gt;&gt; 等)混合通常是个坏主意。
  • 您的订单cmp 不满足std::sort 的要求。
  • @molbdnilo 您可能会比这更有帮助。代码显示if(a.first==a.second),显然意图是if(a.first==b.first)。 OP 可能会很容易地盯着编写的代码,但会按预期看到代码并且永远不会理解您的评论。

标签: c++ algorithm graph


【解决方案1】:

我终于明白了,std::sort cmp 函数中的一点点缺陷,它是

bool cmp(const pair<int,int> a,pair<int,int> b)
{
    if(a.first==b.first)
    return a.second<b.second;
    else
    return a.first<b.first;
}

也在 dfs 函数中使用 low[v]&gt;disc[u] 而不是 low[v]&gt;low[u]

【讨论】:

    猜你喜欢
    • 2015-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-06
    • 1970-01-01
    • 1970-01-01
    • 2022-07-06
    • 1970-01-01
    相关资源
    最近更新 更多