题目大意:每个同学可以指定一个人,然后构成一个有向图。1-n次查询,从某个人开始并放入一个东西,然后循环,直到碰到一个人已经放过了,就输出。
思路:直接模拟就可以了,O(n^2) 但是O(n)也可以实现, 不是太懂大神的思路。
初始化ans[i] = i, 一个点能被输出的话就是 ans[i] = i (可以模拟一下),这个ans是如何算的呢。大神用了topo排序。 记录入度数,然后把入读为0放入队列,取出来然后连接点入度--, ans[i] = p[i] ( p[i] 是 i 指定的人 )直到队列为空。
O(n^2)代码:
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <algorithm>
#include <sstream>
#include <stack>
using namespace std;
#define mem(a,b) memset((a),(b),sizeof(a))
#define mp make_pair
#define pb push_back
#define fi first
#define se second
#define sz(x) (int)x.size()
#define all(x) x.begin(),x.end()
typedef long long ll;
const int inf = 0x3f3f3f3f;
const ll INF =0x3f3f3f3f3f3f3f3f;
const double pi = acos(-1.0);
const double eps = 1e-5;
const ll mod = 1e9+7;
//head
bool vis[1000 + 10];
vector<int> G[1000 + 10];
int main() {
int n, x;
scanf("%d", &n);
for(int i = 1; i <= n; i++) {
scanf("%d", &x);
G[i].push_back(x);
}
for(int i = 1; i <= n; i++) {
mem(vis, false);
vis[i] = true;
int net = G[i][0];
while(vis[net] != true) {
vis[net] = true;
net = G[net][0];
}
printf("%d ", net);
}
}
O(n)代码:
#include<iostream>
#include<queue>
using namespace std;
const int maxn = 1000 + 10;
int p[maxn], ans[maxn], deg[maxn];
int res(int i) {//比较神奇 也就是循环
return i == ans[i] ? i : res(p[i]);
}
int main(int argc, char const *argv[])
{
int n;
scanf("%d", &n);
for(int i = 1; i <= n; i++) {
scanf("%d", &p[i]);//每个点指定的点
deg[p[i]]++;//入读++
}
queue<int> q;
for(int i = 1; i <= n; i++) {//初始化ans
ans[i] = i;
if(deg[i] == 0)//入度为0 进队列
q.push(i);
}
while(!q.empty()){//topo
int u = q.front(); q.pop();
deg[p[u]]--;
ans[u] = p[u];//这里不是太懂(模拟一下比较好)
if(deg[p[u]] == 0)
q.push(p[u]);
}
for(int i = 1; i <= n; i++)
printf("%d ", res(i));
return 0;
}