codeforces div3 D Circular Dance (链式向前星)

题目链接:

http://codeforces.com/contest/1095/problem/D

通过题意可知,每次输入的两个数一定相邻,所有只要对每次输入的两个数看作是边,通过向前星构建无向图,并且题意说明一定有环,所以只要对这个无向图按照一定的方向找环,遇到重复的停止就行了。

代码:

#include <iostream>     //向前星。
#include <stdio.h>
#include <cstring>
using namespace std;
const int inf=2e5+7;
int head[inf],cnt=0;    //顶点数是不用变的。
struct node
{
    int from,to;
    int nxt;
}arr[2*inf];
int ans[inf];

void addedge(int a,int b)
{
    arr[cnt].from=a;
    arr[cnt].to=b;
    arr[cnt].nxt=head[a];
    head[a]=cnt++;
}

int main()
{
    memset(head,-1,sizeof(head));
    int n;
    int a,b,aa,bb;
    scanf("%d",&n);
    for(int i=0;i<n;i++)
    {
        scanf("%d %d",&a,&b);
        if(i==0)
            aa=a,bb=b;
        addedge(a,b);
        addedge(b,a);
    }
    int one=1,flag=0;
    int thenow=2e5+7;
    int p=0;

    while(one!=1||flag==0)
    {
        flag=1;
        //printf("%d ",one);
        ans[p++]=one;
        for(int i=head[one];i!=-1;i=arr[i].nxt)
        {
            int to1=arr[i].to;
            if(to1!=thenow)
            {
                thenow=one;
                one=to1;
                goto x;
            }
            /*for(int j=head[to1];j!=-1;j=arr[j].nxt)
            {
                int to2=arr[j].to;
                if(to2==one)continue;
                else
                {
                    one=to2;
                    goto x;
                }
            }*/
        }
        x:;
    }
    if(ans[1]==aa||ans[2]==aa)
    {
        for(int i=0;i<n;i++)
            printf("%d ",ans[i]);
        printf("\n");
    }
    else
    {
        for(int i=n-1;i>=0;i--)
            printf("%d ",ans[i]);
        printf("\n");
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_40799464/article/details/85841929