题意:国王有n个城市,两两之间至少存在一条有向边相连,现在国王想把这些城市变成发达城市,规则如下:当前变成发达城市的发展中城市必须与所有的发达城市直接相连或者是通过另一个发达城市相连(有向u—>v),求变成发达城市的顺序。
思路:不妨倒这思考,找到一个与所有城市的距离小于二的城市删掉,循环这个过程,而这样会超时(亲身经历)。不妨再换个思路,找到入度最大的点,删掉,循环这个过程。因为两两有边相连,所以每个城市的出度和入度的和都是相等的,找到入度最大的点即可。
代码:
#include <cstdio>
#include <iostream>
#include <cstring>
#include <string>
#include <cmath>
#include <stack>
#include <algorithm>
#define maxn 510
#define inf 1000
using namespace std;
int cnt[maxn];
char dis[maxn][maxn];
stack<int> S;
int main()
{
//freopen("data.in","r",stdin);
int n,maxe,tp;
while (1)
{
scanf("%d",&n);
memset(cnt,0,sizeof(cnt));
if(n==0) break;
for(int i=0;i<n;i++)
{
scanf("%s",dis[i]);
for(int j=0;j<n;j++)
{
if(dis[i][j]=='1')
cnt[j]++;
}
}
for(int i=0;i<n;i++)
{
maxe=-1;
for(int j=0;j<n;j++)
{
if(cnt[j]>maxe)
{
tp=j;
maxe=cnt[j];
}
}
cnt[tp]=-2;
for(int j=0;j<n;j++)
{
if(dis[tp][j]=='1')cnt[j]--;
}
S.push(tp);
}
for(int i=0;i<n;i++)
{
printf("%d ",S.top()+1);
S.pop();
}
puts("");
}
return 0;
}