1651. Shortest Subchain(bfs)

1651

终于A了 

看这题容易想到最短路 看到错的很多 还特意注意了好几处

后来发现 必须按给出的顺序出边 想了想 这不就是BFS 

然后就是各种细节 i->i+1ori->j(a[i]==a[j])

 

 1 #include <iostream>

 2 #include<cstdio>

 3 #include<cstring>

 4 #include<algorithm>

 5 #include<stdlib.h>

 6 #include<queue>

 7 #include<vector>

 8 using namespace std;

 9 #define N 10010

10 #define INF 0xfffffff

11 vector<int>ed[N];

12 vector<int>::iterator it;

13 int vis[N*10],pa[N*10],a[N*10],o[N*10],f[N*10];

14 int n,ff[N*10];

15 struct node

16 {

17     int x,num;

18 };

19 void bfs(int s,int e)

20 {

21     int i,oo,minz = INF;

22     queue<node>q;

23     node st,te;

24     st.x = s;

25     st.num = 0;

26     pa[s] = s;

27     q.push(st);

28     while(!q.empty())

29     {

30         te = q.front();

31         int u = te.x;

32         q.pop();

33         if(te.num>minz)

34         continue;

35         if(a[u]==e)

36         {

37             minz = te.num;

38             oo = u;

39             continue;

40         }

41         if(ff[u]&&!vis[ff[u]])

42         {

43             int v = ff[u];

44             if(!vis[v])

45             {

46                 vis[v] = 1;

47                 st.x = v;

48                 st.num = te.num;

49                 q.push(st);

50                 pa[v] = pa[u];

51             }

52         }

53         if(!vis[u+1]&&u<n)

54         {

55             vis[u+1] = 1;

56             st.x = u+1;

57             st.num = te.num+1;

58             q.push(st);

59             pa[u+1] = u;

60         }

61     }

62     int x = oo,g=1;

63     o[g++] = a[oo];

64     while(x!=s)

65     {

66         x = pa[x];

67         o[g++] = a[x];

68     }

69     for(i = g-1 ; i >= 1; i--)

70     if(o[i]!=o[i+1])

71     printf("%d ",o[i]);

72     puts("");

73 }

74 int main()

75 {

76     int i;

77     scanf("%d",&n);

78     for(i =1; i <= n ; i++)

79     {

80         scanf("%d",&a[i]);

81         if(f[a[i]])

82         {

83             ff[f[a[i]]] = i;

84             f[a[i]] = i;

85         }

86         else

87         f[a[i]] = i;

88     }

89     bfs(1,a[n]);

90     return 0;

91 }
View Code

 

你可能感兴趣的:(chain)