基于bfs的:hdu1285
有N个比赛队(1<=N<=500),编号依次为1,2,3,。。。。,N进行比赛,比赛结束后,裁判委员会要将所有参赛队伍从前往后依次排名,但现在裁判委员会不能直接获得每个队的比赛成绩,只知道每场比赛的结果,即P1赢P2,用P1,P2表示,排名时P1在P2之前。现在请你编程序确定排名。
#include<bits/stdc++.h>
#define js ios::sync_with_stdio(false)
#define mes(a,b) memset(a,b,sizeof a)
using namespace std;
typedef long long ll;
priority_queue<int,vector<int>,greater<int> >q; //存当前入度为0的点
vector<int>uu[505]; //存以u为起点的边;
int digt[505]; //存每个点的入度
int main() {
int n,m,u,v;
js;
while(cin>>n>>m) {
mes(digt,0);
for(int i=1;i<=n;++i)
uu[i].clear();
for(int i=0;i<m;++i) {
cin>>u>>v;
uu[u].push_back(v);
digt[v]++;
}
for(int i=1;i<=n;++i)
if(!digt[i])
q.push(i);
int flag=0;
while(!q.empty()) {
u=q.top(); q.pop();
for(int i=0;i<uu[u].size();++i)
if(!--digt[uu[u][i]])
q.push(uu[u][i]);
if(flag) cout<<" "<<u;
else {
flag=1;
cout<<u;
}
}
cout<<endl;
}
}基于dfs的:poj1270
第一列给出所有的字母数,第二列给出一些先后顺序。然后按字典序最小的方式输出所有的可能性
#include<cstdio>
#include<cstring>
#define js ios::sync_with_stdio(false)
#define mes(a,b) memset(a,b,sizeof a)
using namespace std;
typedef long long ll;
int n;
int g[30][30];
int ans[25];
int cnt;
bool mark[30];
bool vis[30];
bool ok(int i,int cnt) {
for(int j=0;j<cnt;++j)
if(g[i][ans[j]]) return false;
return true;
}
void dfs(int cnt) {
if(cnt==n) {
for(int i=0;i<cnt;++i)
printf("%c",ans[i]+'a');
puts("");
}
else {
for(int i=0;i<26;++i)
if(mark[i]&&!vis[i]&&ok(i,cnt)) {
ans[cnt]=i;
vis[i]=1;
dfs(cnt+1);
vis[i]=0;
}
}
}
int main() {
char str[300];
while(gets(str)) {
n=0;
mes(g,0);
mes(mark,0);
for(int i=0;str[i];++i) if(str[i]!=' ')
mark[str[i]-'a']=true, n++;
gets(str);
for(int i=0;i<strlen(str);i+=2) {
int a=str[i]-'a';
i+=2;
int b=str[i]-'a';
g[a][b]=1;
}
dfs(0);
puts("");
}
return 0;
}
京公网安备 11010502036488号