UVAL 1651 Shortest Subchain(构图+spfa)

1651. Shortest Subchain

Time limit: 1.0 second
Memory limit: 64 MB
UVAL 1651 Shortest Subchain(构图+spfa)_第1张图片
A chain  p is given in a directed graph without loops or multiple edges. It is required to specify its subchain  q such that
  • the initial and final vertices of the chains p and q coincide;
  • the edges in the chain q are in the same order as in the chain p;
  • the chain q has the minimal possible number of edges under the given conditions.

Input

The chain  p is given by the list of its vertices. The first line contains the number  n of vertices in the list, 2 ≤  n ≤ 100000 (thus, the length of the chain is  n−1). The following lines contain  n numbers of vertices (they are integers in the range from 1 to 10000). The numbers are separated by spaces or linebreaks. No two successive vertices in the list coincide.

Output

Output the vertices of the chain  q by giving their numbers separated by a space. Chain  q may consist of single a vertex.

Sample

input output
9
1 2 7 3 2
8 4 8 5
1 2 8 5
Problem Author: Vladimir Yakovlev (idea by Magaz Asanov)
Problem Source: NEERC 2008, Eastern subregion quarterfinals

题意:给一条链你,要求找出一条开头和末尾和原来一样的最短的链
题解:把给出来的点当一条长度为 1路径,然后相同的点再连一条长度为0的路径,然后求一次最短路输出路径就可以了

#include
#include
#define INF 0xfffffff
struct edge{
    int data,next,len;
}p[200005];
int mark[10005],a[100005],pre[100005];
int all,n,que[900005],head[100005],dis[100005];
void add(int x,int y,int len)
{
    p[all].next=head[x];
    p[all].data=y;
    p[all].len=len;
    head[x]=all++;
}
void spfa()
{
    int sta=0,fin=0,now,i,x;

    for(dis[0]=0,i=1;i<=n;i++) dis[i]=INF;
    que[fin++]=0;  pre[0]=-1;
    while(sta0)
    {
        for(i=0;i0&&a[i]==que[all-1]) continue;
            que[all++]=a[i];
        }
        printf("%d",que[all-1]);
        for(i=all-2;i>=0;i--) printf(" %d",que[i]);
        printf("\n");
    }

    return 0;
}


你可能感兴趣的:(ACM之路(c/c++),图论)