炸铁路

题目描述 因为某国被某红色政权残酷的高压暴力统治。美国派出将军uim,对该国进行战略性措施,以解救涂炭的生灵。

该国有n个城市,这些城市以铁路相连。任意两个城市都可以通过铁路直接或者间接到达。

uim发现有些铁路被毁坏之后,某两个城市无法互相通过铁路到达。这样的铁路就被称为key road。

uim为了尽快使该国的物流系统瘫痪,希望炸毁铁路,以达到存在某两个城市无法互相通过铁路到达的效果。

然而,只有一发炮弹(美国国会不给钱了)。所以,他能轰炸哪一条铁路呢?

输入输出格式 输入格式: 第一行n,m(1<=n<=150, 1<=m<=5000),分别表示有n个城市,总共m条铁路。

以下m行,每行两个整数a, b,表示城市a和城市b之间有铁路直接连接。

输出格式: 输出有若干行。

每行包含两个数字a,b(a<b),表示<a,b>是key road。

请注意:输出时,所有的数对<a,b>必须按照a从小到大排序输出;如果a相同,则根据b从小到大排序。

输入输出样例 输入样例#1: 复制 6 6 1 2 2 3 2 4 3 5 4 5 5 6 输出样例#1: 复制 1 2 5 6

邻接表+SPFA+sort排序(正解)

搜索 O(n^2),刚刚卡到;

#include<cstdio>
#include<iostream>
#include<cmath>
#include<algorithm>
using namespace std;

int n,m,peng[151],b[151];

struct node{
    int x;
    int y;
}a[501];

inline int find(int x){
    if(peng[x]==x){
        return x;
    }
    return peng[x]=find(peng[x]);
}

inline void hhh(int x,int y){
    int x1=find(x);
    int y1=find(y);
    peng[y1]=peng[x1];
}

inline bool cmp(node x,node y){
    if(x.x==y.x){
        return x.y<y.y;
    }
    return x.x<y.x;
}

int main(){
    int i,j;
    ios::sync_with_stdio(false);
    scanf("%d%d",&n,&m);
    for(i=1;i<=m;i++){
        scanf("%d%d",&a[i].x,&a[i].y);
        if(a[i].y<a[i].x){
            swap(a[i].x,a[i].y);
        }
    }
    sort(a+1,a+m+1,cmp);
    for(i=1;i<=m;i++){
        for(j=1;j<=n;j++){
            peng[j]=j;
        }
        for(j=1;j<=m;j++){
            if(j!=i){
                hhh(a[j].x,a[j].y);
            }
        }
        for(j=2;j<=n;j++){
            if(peng[find(j)]!=peng[find(j-1)]){
                printf("%d %d
",a[i].x,a[i].y);
                break;
            }
        }
    }
    return 0;
}
原文地址:https://www.cnblogs.com/hrj1/p/11139443.html