Gordon1 @ 2024-11-21 18:58:16
#include<bits/stdc++.h>
using namespace std;
int init[110];
vector<int> a[110];
vector<int> ans;
queue<int> r;
int n;
int aa;
int main()
{
cin>>n;
for(int i=1;i<=n;++i)
{
while(cin>>aa&&aa!=0)
{
a[i].push_back(aa);
init[aa]++;
}
}
for(int i=1;i<=n;++i)
{
if(init[i]==0) r.push(i);
}
while(r.size())
{
int now=r.front();
r.pop();
ans.push_back(now);
for(int i=1;i<=a[now].size();++i)
{
init[a[now][i]]--;
if(init[a[now][i]]==0) r.push(a[now][i]);
}
}
for(int i=1;i<=n;++i)
cout<<ans[i]<<" ";
return 0;
}
by dingxiongyue @ 2024-11-22 17:29:18
@Gordon1
动态数组vector的下标是从0开始的(详见代码24 29行)
#include<bits/stdc++.h>
using namespace std;
int init[110];
vector<int> a[110];
vector<int> ans;
queue<int> r;
int n;
int aa;
int main() {
cin >> n;
for (int i = 1; i <= n; ++i) {
while (cin >> aa && aa != 0) {
a[i].push_back(aa);
init[aa]++;
}
}
for (int i = 1; i <= n; ++i) {
if (init[i] == 0) r.push(i);
}
while (r.size()) {
int now = r.front();
r.pop();
ans.push_back(now);
//for(int i = 1; i <= a[now].size(); ++i){
for (int i = 0; i < a[now].size(); ++i) {
init[a[now][i]]--;
if (init[a[now][i]] == 0) r.push(a[now][i]);
}
}
//for(int i = 1; i <= n; ++i)
for (int i = 0; i < n; ++i)
cout << ans[i] << " ";
return 0;
}
自测已过
by Gordon1 @ 2024-11-23 09:06:58
@dingxiongyue感谢大佬,已关