算法竞赛入门经典第六章总结
并行程序模拟:
#include<iostream> #include<cstdio> #include<queue> #include<cstring> #include<algorithm> using namespace std; const int maxn = 1010; deque<int>wait; queue<int>block; int line,quan; int pgline[100]; char pgcmd[maxn][10]; int val[26]; int t[5],locked; void run(int num); int main(void) { memset(pgline,0,sizeof(pgline)); memset(pgcmd,0,sizeof(pgcmd)); memset(val,0,sizeof(val)); int n; cin >> n; for(int i=0;i<5;i++) cin >> t[i]; cin >> quan; for(int i=0;i<n;i++) { gets(pgcmd[line++]); pgline[i]=line-1; while(pgcmd[line-1][2]!='d') gets(pgcmd[line++]); wait.push_back(i); } locked=0; while(!wait.empty()) { int pick = wait.front(); wait.pop_front(); run(pick); } return 0; } void run(int num) { int q=quan; while(q>0) { char *str=pgcmd[pgline[num]]; switch(str[2]) { case '=': val[str[0]-'a']=isdigit(str[5])?(str[4]-'0')*10+(str[5]-'0'):str[4]-'0'; q-=t[0]; break; case 'i': printf("%d : %d\n",num+1,val[str[6]-'0']); q-=t[1]; break; case 'c': if(locked){ block.push(num); return ; } locked=1; q-=t[2]; break; case 'l': locked=0; if(!block.empty()) { wait.push_front(block.front()); block.pop(); } q-=t[3]; break; case 'd': return ; } pgline[num]++; } }
铁轨:
#include<stack> #include<iostream> #include<cstdio> using namespace std; const int maxn = 1010; stack<int>s; int ans[maxn]; int main(void) { int n; cin >> n; for(int i=1;i<=n;i++) cin >> ans[i]; int A=1,B=1,ok=1; while(B<=n) { if(A==ans[B]) { A++,B++; } else if(!s.empty() && s.top()==ans[B]) { B++; s.pop(); } else if(A<=n) { s.push(A++); } else { ok = 0; break; } } //cout << ok?"YES":"NO" << endl; printf("%s\n",ok?"YES":"NO"); return 0; }
矩阵链乘:
#include<iostream> #include<stack> #include<cstdio> #include<string> #include<algorithm> using namespace std; struct Matrix{ int a,b; Matrix(int a=0,int b=0):a(a),b(b){} }m[26]; stack<Matrix>s; int main(void) { int n; cin >> n; for(int i=0;i<n;i++) { string name; cin >> name; int k=name[0]-'A'; cin >> m[k].a >> m[k].b; } string expr; while(cin >> expr) { int len=expr.length(); bool error = false; int ans = 0; for(int i=0;i<len;i++) { if(isalpha(expr[i])) s.push(m[expr[i]-'A']); else if(expr[i]==')') { Matrix m2=s.top(); s.pop(); Matrix m1=s.top(); s.pop(); if(m1.b!=m2.a){ error=true; break; } ans+=m1.a*m1.b*m2.b; s.push(Matrix(m1.a,m2.b)); } } if(error) printf("error\n"); else printf("%d\n",ans); } }