UVA10557-XYZZY
就是找正环,再找路径,详细的待以后再讨论
先贴上代码:
dfs+dfs:
#include <iostream> #include <cstring> using namespace std; struct Room{ int value,count; int list[100]; }; Room room[150]; int n, value[150], visit[150] = {0, 0, 0};; void input() { for(int i = 1; i <= n; i++) { cin>>room[i].value>>room[i].count; int len = room[i].count; for(int j = 0; j < len; j++) cin>>room[i].list[j]; value[i] = 0; } } int ddfs(int u) { if(u==n)return 1; for(int i = 0; i < room[u].count; i++) { if(!visit[room[u].list[i]]){ visit[room[u].list[i]] = 1; if(ddfs(room[u].list[i])) return 1;} } return 0; } int dfs(int u, int e) { if(e<=0)return 0; if(u==n)return 1; value[u] = e + room[u].value; for(int i = 0; i < room[u].count; i++) { if(!value[room[u].list[i]]){if(dfs(room[u].list[i],e+room[u].value)) return 1;} else if(value[u]+room[room[u].list[i]].value>value[room[u].list[i]]&&memset(visit,0,sizeof(visit)),ddfs(room[u].list[i])) return 1; } return 0; } int main () { while(cin>>n&&n!=-1) { input(); if(dfs(1,100))cout<<"winnable"<<endl; else cout<<"hopeless"<<endl; } return 0; }
dfs+bfs:
#include <iostream> using namespace std; struct Room{ int value,count; int list[100]; }; Room room[150]; int n, value[150]; void input() { for(int i = 1; i <= n; i++) { cin>>room[i].value>>room[i].count; int len = room[i].count; for(int j = 0; j < len; j++) cin>>room[i].list[j]; value[i] = 0; } } int bfs(int u) { int q[150], visit[150] = {0, 0, 0}; int front = 0, rear = 0; q[0] = u; while(front>=rear) { int r = q[rear]; for(int i = 0; i < room[r].count; i++) { if(visit[room[r].list[i]])continue; if(room[r].list[i]==n)return 1; q[++front] = room[r].list[i]; visit[room[r].list[i]] = 1; } rear++; } return 0; } int dfs(int u, int e) { if(e<=0)return 0; if(u==n)return 1; value[u] = e + room[u].value; for(int i = 0; i < room[u].count; i++) { if(!value[room[u].list[i]]){if(dfs(room[u].list[i],e+room[u].value)) return 1;} else if(value[u]+room[room[u].list[i]].value>value[room[u].list[i]]&&bfs(room[u].list[i])) return 1; } return 0; } int main () { while(cin>>n&&n!=-1) { input(); if(dfs(1,100))cout<<"winnable"<<endl; else cout<<"hopeless"<<endl; } return 0; }
都是16秒过的、