拓扑排序的head数组为什么不是vector?
  • 板块P1347 排序
  • 楼主rome1
  • 当前回复5
  • 已保存回复5
  • 发布时间2023/12/31 15:13
  • 上次更新2023/12/31 17:58:45
查看原帖
拓扑排序的head数组为什么不是vector?
1159426
rome1楼主2023/12/31 15:13
#include<bits/stdc++.h>
#define N 610
using namespace std;
int a,b,n,m,s,sum,tot,head[N],in[N],inn[N],p[N];
bool v,unpd,vis[N];
queue<int>q;
char ch;
struct Edge
{
    int from,to,next;
}edge[N];
int add(int x,int y)
{
    tot++;
    edge[tot].to=y;
    edge[tot].next=head[x];
    head[x]=tot;
}
int tp()
{
    unpd=false;v=false;sum=0;
    for(int i=1;i<=26;i++)
     {
         inn[i]=in[i];
         if(!inn[i]&&vis[i])
          {
              if(!v) v=true;
              else unpd=true;
              q.push(i);
              p[++sum]=i;
           } 
      } 
    if(q.empty()) return 1; 
    while(!q.empty()) 
    {
        int x=q.front();v=false;q.pop();
        for(int i=head[x];i;i=edge[i].next)
        {
            inn[edge[i].to]--;
            if(!inn[edge[i].to])
            {
                q.push(edge[i].to);
                if(!v) v=true;
                else unpd=true;
                p[++sum]=edge[i].to;
            } 
        }
    }
    if(sum!=s) return 1;
    if(unpd) return 2;
    return 0; 
}
int main()
{
    cin>>n>>m;
    for(int i=1;i<=m;i++)
    {
        cin>>ch,a=ch-64;if(!vis[a])vis[a]=true,s++;
        cin>>ch;
        cin>>ch,b=ch-64;if(!vis[b])vis[b]=true,s++;
        add(a,b);
        in[b]++; 
        if(tp()==1) 
        {
            printf("Inconsistency found after %d relations.",i); 
            return 0;
        }
        if(sum==n&&!tp())
        {
            printf("Sorted sequence determined after %d relations: ",i);
            for(int j=1;j<=n;j++) printf("%c",p[j]+64);
            printf(".");
            return 0;
        }
    }
    printf("Sorted sequence cannot be determined.");
    return 0;
}

head不应该存的是一个点延伸出的所有边吗 这样不会让后来的边替代了前面的边??

2023/12/31 15:13
加载中...