POJ 1094

来源:互联网 发布:2015年网络歌曲 编辑:程序博客网 时间:2024/06/10 05:25


说明:代码学习于优秀的网友,注释是我写的  ,如果哪里有错误  ,欢迎指正

POJ 1094:题意:有一些未知数各不相等,给出一些两两比较的大小关系,问到第几个关系开始可以确定整体排序或出现矛盾,再或者所有关系都用过了也无法确定整体排序。


拓扑排序 的思想: 从图中取一个没有前驱的顶点输出,  从有向图中删去此顶点以及所有以它为尾的弧 。 要求是有向无环图,图中顶点是线性排列关系

邻接矩阵(用数组存储图的方式):采用两个数组,一个数组用来存储顶点信息   另一个数组用来存储数据元素之间的关系

一般如下定义:

map[max][max];

for(int i;i<m;i++)//m,n根据自己的需要来确定

{

     for(int j;i<n;j++)

          {

           }

}

-----------------------------------------------------------------------------------------------------------------------------------------------

#include<iostream>
#include<cstdio>
#include<stdio.h>
#include<cstdlib>
#include<cstring>
#include<string.h>
#include<algorithm>
using namespace std;

#define  maxn  30   //宏定义
int n, m; //分别代表顶点数和边数
bool smaller[maxn][maxn];//用来存储最后拓扑顺序的结果
enum Result   //枚举结果的类型
{
 inconsistent, determined, undetermined  //分别代表有矛盾的   确定的, 不确定的
};

int get_id(char a)//把ASC码值转换成数值
{
 return a - 'A';
}

Result  work(int a, int b)
{
 int i,j;
 if (smaller[b][a])//如果现在输入的值在存储结果的数组中已经存在,则是结果为矛盾
 {
  return  inconsistent;
 }
 smaller[a][b]=true;//不然就把该条件输入到结果中进行排序
 for (i = 0; i <n; i++)//对结果数组中的顶点进行判断,确定顶点
 {
  if (smaller[i][a])
  {
   smaller[i][b] = true;
  }
 }
 for ( i = 0; i <n; i++)
 {
  if (smaller[b][i])
  {
   smaller[a][i] = true;
  }
 }
 for ( i = 0; i <n; i++)//根据条件确定顶点之间的关系
 {
  for ( j = 0; j < n; j++)
  {
   if (smaller[i][a] && smaller[b][j])
   {
    smaller[i][j] = true;
   }
  }
 }
 for ( i = 0; i < n; i++)
 {
  for ( j = i+1; j < n; j++)
  {
   if (!(smaller[i][j]||smaller[j][i]))
   {
    return  undetermined;
   }
  }
 }
 return  determined;  //如果根据已知的条件得到了结果,返回已确定答案
}

void  input(int x) 
{
 char st[5];
 for (int i = x + 1; i < m; i++)
 {
  gets(st);
 }
}

bool cmp(int a, int b)
{
 return smaller[a][b];
}

void output()
{
 int f[maxn];
 int i;
 for ( i = 0; i < n; i++)
 {
  f[i] = i;
 }
 sort(f, f + n, cmp);
 for(i = 0; i < n; i++)
 {
  putchar(f[i] + 'A');
 }
}


int main()
{
 while (scanf("%d%d",&n,&m),n|m)  //输入顶点数跟给出的条件的个数
 {
  int i;
  getchar();  //得到字符
  memset(smaller, 0, sizeof(smaller));//对用来存储结果的数组清空
  Result ans = undetermined;  //定义一个结果的对象
  for ( i = 0; i <m; i++)
  {
   char a, b, opr;
   a = getchar();//用来获取输入的第一个条件的字符
   opr = getchar();//用来获取输入的第二个条件的字符
   b = getchar();//用来获取输入的第三个条件的字符
   getchar(); //用来接收空格
   if (opr == '<') //如果满足条
   {
    ans = work(get_id(a),get_id(b));//调用work函数,及get_id,得到某种结果
   }
   else
   {
    ans = work(get_id(b), get_id(a));
   }
   if (ans==inconsistent)//根据返回的结果进行相应格式的输出
   {
    printf("Inconsistency found after %d relations.\n", i + 1);
    input(i);//用来得到顶点数
    break;
   }
   if (ans==determined)
   {
    printf("Sorted sequence determined after %d relations: ", i + 1);
    input(i);
    output();
    cout << "." << endl;
    break;
   }
  }
  if (ans==undetermined)
  {
   puts("Sorted sequence cannot be determined.");
  }
 }
 system("pause");
 return  0;
}

0 0