Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 24697 | Accepted: 8557 |
Description
Input
Output
Sorted sequence determined after xxx relations: yyy...y.
Sorted sequence cannot be determined.
Inconsistency found after xxx relations.
where xxx is the number of relations processed at the time either a sorted sequence is determined or an inconsistency is found, whichever comes first, and yyy...y is the sorted, ascending sequence.
Sample Input
4 6 A<B A<C B<C C<D B<D A<B 3 2 A<B B<A 26 1 A<Z 0 0
Sample Output
Sorted sequence determined after 4 relations: ABCD. Inconsistency found after 2 relations. Sorted sequence cannot be determined.
這道題雖然是一道拓撲排序的基本題,但是依然浪費了主頁君一天來攻擊這道題,這道題其實意思很簡單,更具上面給出的關係求出一個整體關係,即給出N個字母,再給出字母之間大小關係,然後如果可以從大到小排序,則輸出整體排序,如果對應關係矛盾,輸出有矛盾,如果有不止一個對應關係,則輸出存在多組對應關係,這道題其實運用拓撲算法,並且需要對拓撲算法進行一定修改,並且運用floyd看題目中是否有矛盾,判定方法就是求出全源對應關係,之後如果相同節點有大小對應關係,則證明題目存在矛盾,之後對數列帶入拓撲算法,判斷當尋找父節點爲0的根節點時,發現有多個根節點,則證明對應關係不止一種,直接跳出函數繼續更新路徑後重新帶拓撲排序,如果沒有再發現根節點但是已排序節點數小於總結點數,則證明存在環路,即有矛盾,輸出存在矛盾,之後的拓撲模板則不需要繼續修改了,直接得到拓撲序列,並且輸出即可AC,這道題其實也是道難度相對較大的題,各種關係量要注意分析的步驟,否則很容易因爲粗心造成一定麻煩。
下面是AC代碼:
#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;
int G[30][30],ans[30],degree[30],into[30],visit[30];
int Floyd_Washall(int n)
{
int i,j,k;
for (k=0;k<n;k++)
for (i=0;i<n;i++)
for (j=0;j<n;j++)
if (G[i][j]==0&&G[i][k]==1&&G[k][j]==1)
G[i][j]=1;
for(i=1;i<=n;i++)
if(G[i][i]==1)
return 1;
return 0;
}
int Toplogical_sort(int n)
{
int i,j,top,count;
bool p=true;
top=0;
memset(visit,0,sizeof(visit));
memset(degree,0,sizeof(degree));
memset(ans,0,sizeof(ans));
for(i=0;i<n;i++)
for(j=0;j<n;j++)
if(G[i][j]==1)
degree[j]++;
for(i=0;i<n;i++)
{
count=0;
for(j=0;j<n;j++)
if(degree[j]==0&&visit[j]==0)
{
count++;
top=j;
}
if(count>=2)
return 0;
else if(count==0)
return 1;
ans[i]=top;
visit[top]=1;
for(j=0;j<n;j++)
degree[j]--;
}
return 2;
}
int main()
{
int n,m,i,a,b,flag;
char str[400][5];
while(1)
{
flag=0;
memset(G,0,sizeof(G));
cin>>n>>m;
if(n==0&&m==0)
break;
for(i=0;i<m;i++)
scanf("%s",str[i]);
for(i=0;i<m;i++)
{
a=str[i][0]-'A';
b=str[i][2]-'A';
G[a][b]=1;
flag=Floyd_Washall(n);
if(flag==1)
break;
flag=Toplogical_sort(n);
if(flag==2)
break;
}
if(flag==1)
printf("Inconsistency found after %d relations.\n",i+1);
else if(flag==0)
printf("Sorted sequence cannot be determined.\n");
else
{
printf("Sorted sequence determined after %d relations: ",i+1);
for(i=0;i<n;i++)
printf("%c",ans[i]+'A');
printf(".\n");
}
}
return 0;
}