1651. Shortest Subchain
Time limit: 1.0 second
Memory limit: 64 MB
Memory limit: 64 MB
![Problem illustration](https://i-blog.csdnimg.cn/blog_migrate/08c84092a25cee6f7c05ec0a3713707f.png)
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
Problem Source: NEERC 2008, Eastern subregion quarterfinals
题意:给一条链你,要求找出一条开头和末尾和原来一样的最短的链
题解:把给出来的点当一条长度为 1路径,然后相同的点再连一条长度为0的路径,然后求一次最短路输出路径就可以了
#include<stdio.h>
#include<string.h>
#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(sta<fin)
{
now=que[sta++];
for(i=head[now];i!=-1;i=p[i].next)
{
x=p[i].data;
if(dis[now]+p[i].len<dis[x])
{
dis[x]=dis[now]+p[i].len;
que[fin++]=x; pre[x]=now;
}
}
}
}
int main()
{
int i;
//freopen("t","r",stdin);
while(scanf("%d",&n)>0)
{
for(i=0;i<n;i++)
{
scanf("%d",a+i);
head[i]=-1;
}
memset(mark,-1,sizeof(mark));
mark[a[0]]=0;
for(all=i=0;i<n-1;i++)
{
add(i,i+1,1);
if(mark[a[i+1]]!=-1) add(mark[a[i+1]],i+1,0);
mark[a[i+1]]=i+1;
}
spfa();
for(all=0,i=n-1;i!=-1;i=pre[i])
{
if(all>0&&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;
}