poj 1789 트럭 역사 (kruskal 알고리즘)

3969 단어 history
테마 링크: http://poj.org/problem?id=1789
사고: 하나의 점, 두 줄 사이 에 문자 의 개 수 를 모 르 면 가중치 로 간주한다.그리고 kruskal 알고리즘 으로 최소 생 성 트 리 를 계산 합 니 다.
나 는 두 개의 코드 를 썼 다. 하 나 는 우선 대기 열 로 쓴 것 이다.그런데 시간 이 초과 됐어 요. 왜 그런 지 모 르 겠 어 요.누 군가 풀 어 줬 으 면 좋 겠 어 요.뒤에 사용 할 배열 sort 정렬 하고 AC.
code:
배열 sort 정렬 AC 코드:
#include<cstdio>
#include<queue>
#include<algorithm>
#include<iostream>

using namespace std;

struct edge
{
    int from;
    int to;
    int cost;
};


bool cmp(edge e1,edge e2)
{
    return e1.cost<e2.cost;
}

edge node[2001*2001];

int father[2005];
int nn,n;

int find(int x)             //      
{
    if(x!=father[x])
    {
        father[x]=find(father[x]);
    }
    return father[x];
}

void kruskal()
{
    int MST=0;
    for(int i=0;i<2005;i++)
    {
        father[i]=i;
    }
    for(int i=0;i<nn;i++)
    {
        int fx=find(node[i].from);
        int fy=find(node[i].to);
        if(fx!=fy)
        {
            father[fx]=fy;
            MST+=node[i].cost;
        }
    }
    printf("The highest possible quality is 1/%d.
",MST); } int main() { char str[2005][10]; int i,j; while(scanf("%d",&n)==1&&n) { nn=0; for(i=0;i<n;i++) { scanf("%s",str[i]); } for(i=0;i<n;i++) { for(j=0;j<i;j++) { int sum=0; for(int kk=0;kk<7;kk++) { if(str[i][kk]!=str[j][kk]) { sum++; } } node[nn].from=i; node[nn].to=j; node[nn].cost=sum; nn++; } } sort(node,node+nn,cmp); kruskal(); } return 0; }
우선 대기 열 시간 초과 코드
#include<cstdio>
#include<queue>
#include<algorithm>
#include<iostream>

using namespace std;

struct edge
{
    friend bool operator<(edge e1,edge e2)
    {
        return e1.cost>e2.cost;
    }
    int from;
    int to;
    int cost;
};

edge e;
priority_queue<edge> Q;
int father[2005];
int nn,n;
int find(int x)
{
    if(x!=father[x])
    {
        father[x]=find(father[x]);
    }
    return father[x];
}

void kruskal()
{
    int MST=0;
    for(int i=0;i<2005;i++)
    {
        father[i]=i;
    }
    int num=0;
    while(!Q.empty()&&num!=nn)
    {
        edge e=Q.top();
        //printf("BBB%d %d %d
",e.from,e.to,e.cost); Q.pop(); int fx=find(e.from); int fy=find(e.to); if(fx!=fy) { father[fx]=fy; MST+=e.cost; num++; } } printf("The highest possible quality is 1/%d.
",MST); } int main() { char str[2005][10]; int i,j; while(scanf("%d",&n)==1&&n) { nn=0; while(!Q.empty()) Q.pop(); for(i=0;i<n;i++) { scanf("%s",str[i]); } for(i=0;i<n;i++) { for(j=0;j<i;j++) { int sum=0; for(int kk=0;kk<7;kk++) { if(str[i][kk]!=str[j][kk]) { sum++; } } nn++; e.from=i; e.to=j; e.cost=sum; Q.push(e); //printf("edge:%d %d %d %d
",e.from,e.to,e.cost,nn); } } kruskal(); } return 0; }
저작권 성명: 본 블 로그 의 오리지널 글, 블 로그, 동의 없 이 전재 할 수 없습니다.

좋은 웹페이지 즐겨찾기