在我的AKBAR Spoj问题代码中找不到错误

时间:2019-12-29 13:11:42

标签: breadth-first-search

算法:

  1. 从每个已经分配了士兵的城市进行BFS。跟踪每个城市的保护者数量。
  2. 如果它变得> 1,则断开并打印“否”,否则在所有bfs完成后检查一些不受保护的城市。
  3. 如果找到不受保护的打印件“否”,否则打印“是”。

链接到问题:- https://www.spoj.com/status/ns=25150439

#include <bits/stdc++.h>
using namespace std;

#define int long long int
const int INF = 0x3f3f3f3f;

int32_t main()
{
    int t;
    cin>>t;
    while(t--)
    {
        int n, r, m;
        cin>>n>>r>>m;
        vector< vector<int> > adj(n+1, vector<int> (n+1, 0));//adjacency Matrix
        for(int i=0;i<r;i++)
        {
            int x, y;
            cin>>x>>y;
            adj[x][y] = 1;
            adj[y][x] = 1;
        }
        vector<int> protect(n+1, 0); // protect[i] :- number of protectors of city i
        vector<int> assigned(n+1, -1);// assigned[i] :- strength of soldier assigned to city i, if not assigned then -1.
        for(int i=0;i<m;i++)
        {
            int x, y;
            cin>>x>>y;
            assigned[x] = y;
            protect[x] = 1;
        }

        int exflag = 0; // flag to exit when protectors of city become > 1
        for(int s=1;s<n+1;s++)
        {
            if(assigned[s] != -1) // if city is assigned a soldier, then carry bfs
            {
                queue<int> q;
                vector<int> visited(n+1, 0);
                vector<int> distance(n+1, INF);
                q.push(s);
                visited[s] = 1;
                distance[s] = 0;
                while(!q.empty())
                {
                    int u = q.front();
                    q.pop();
                    for(int i=1;i<n+1;i++)
                    {
                        if(adj[u][i] == 1 && visited[i] == 0)
                        {
                            distance[i] = distance[u] + 1;
                            if(distance[i] <= assigned[s])
                            {
                                q.push(i);
                                visited[i] = 1;
                                protect[i]++;
                            }
                            if(protect[i] == 2)
                            {
                                cout<<"No"<<endl;
                                exflag = 1;
                                break;
                            }
                        }
                    }
                    if(exflag)
                    {
                        break;
                    }
                }
                if(exflag)
                {
                    break;
                }
            }
        }

        if(!exflag)
        {
            int flag = 0; // to check if some city is unprotected
            for(int i=1;i<n+1;i++)
            {
                if(protect[i] == 0)
                {
                    flag = 1;
                    cout<<"No"<<endl;
                    break;
                }
            }
            if(!flag) cout<<"Yes"<<endl;
        }
    }
    return 0;
}

0 个答案:

没有答案