考研各大學程式設計題
阿新 • • 發佈:2020-08-19
川大2007年
1、求平均值的遞迴
float Average(float A[],int n)
{
if(n==0) return 0;
if(n == 1)
return A[n-1];
else
return (A[n-1]+(n-1)*Average(A,n-1))/n;
}
2、字串轉換成整數
int Atol(char *strNum) { int flag = 1; int i,n,num = 0 ; for(i = 0; strNum[i] != '\0';i++) { if(strNum[i] == '-') flag = -flag; if(strNum[i] >='0' && strNum[i] <= '9') { num = num * 10 + strNum[i] - '0'; } } return flag == -1 ? -num : num; }
3、實現拓撲排序
#include <cstdio> #include <cstring> #include <cstdlib> #include <algorithm> #include <vector> using namespace std; int main() { int n,m,x,y; cin>>n>>m; vector<vector<int>> v(n+1,vector<int>(n+1,0)); vector<bool> visited(n+1,false); vector<int> res; vector<int> indegree(n+1,0); for(int i = 0 ; i < m; i++) { cin>>x>>y; v[x][y] = 1 ; indegree[y]++; } multiset<int> q; for(int i = 1 ; i <= n ; i++) { if(indegree[i] == 0 ) { q.insert(i); visited[i] = true; } } while(!q.empty()) { int cur = *q.begin(); q.erase(q.begin()); res.push_back(cur); for(int i = 0 ; i < v[cur].size(); i++) { if(v[cur][i] == 0) continue; if(--indegree[i] == 0 && !visited[i]) { visited[i] = true; q.insert(i); } } } for(auto i :res) { cout<<i<<" "; } return 0; }