| ||||||||||
| Online Judge | Problem Set | Authors | Online Contests | User | ||||||
|---|---|---|---|---|---|---|---|---|---|---|
| Web Board Home Page F.A.Qs Statistical Charts | Current Contest Past Contests Scheduled Contests Award Contest | |||||||||
为什么老是超时#include <iostream>
using namespace std;
struct graph{
int vexnum;
int **AdMatrix;
};
void Initgraph(graph &G)
{
int i,j;
cin >> G.vexnum;
while(G.vexnum <= 1)
cin >> G.vexnum;
G.AdMatrix = (int **)malloc(G.vexnum*sizeof(int *));
for(i = 0;i < G.vexnum;i++)
G.AdMatrix[i] = (int *)malloc(G.vexnum*sizeof(int));
for(i = 0;i < G.vexnum;i++)
for(j = 0;j < G.vexnum;j++)
{
if(i == j) G.AdMatrix[i][i] = 1;
else G.AdMatrix[i][j] = INT_MAX;
}
}
void InsertEdge(graph &G,int u,int v)
{
G.AdMatrix[u-1][v-1] = G.AdMatrix[v-1][u-1] = 1;
}
void DeleteEdge(graph &G,int u,int v)
{
G.AdMatrix[u-1][v-1] = G.AdMatrix[v-1][u-1] = INT_MAX;
}
int Query(graph G,int u,int v)
{
if(G.AdMatrix[u-1][v-1] < INT_MAX) return 1;
bool *visited = (bool *)malloc(G.vexnum*sizeof(bool));
int *connected = (int *)malloc(G.vexnum*sizeof(int));
int i,j,k;
for(i = 0;i < G.vexnum;i++)
{
connected[i] = G.AdMatrix[u-1][i];
visited[i] = false;
}
visited[u-1] = true;
for(i = 1;i < G.vexnum;i++)
{
k = -1;
for(j = 0;j < G.vexnum;j++)
if(!visited[j] && connected[j] < INT_MAX)
{
visited[j] = true;
k = j;
break;
}
if(j == G.vexnum && k == -1) break;
for(j = 0;j < G.vexnum;j++)
if(!visited[j] && G.AdMatrix[k][j] < INT_MAX)
connected[j] = 1;
}
if(connected[v-1] < INT_MAX)
{
return 1;
}
return 0;
}
int main()
{
graph G;
Initgraph(G);
int num,i,j;
cin >> num;
char **str = (char **)malloc(num*sizeof(char *));
for(i = 0;i < num;i++)
str[i] = (char *)malloc(3*sizeof(char));
for(i = 0;i < num;i++)
{
for(j = 0;j < 3;j++)
cin >> str[i][j];
while(str[i][0] !='I' && str[i][0] !='D'&&str[i][0]!='Q')
{
for(j = 0;j < 3;j++)
cin >> str[i][j];
}
}
for(i = 0;i < num;i++)
{
if(str[i][0] == 'I') InsertEdge(G,str[i][1]-'0',str[i][2]-'0');
else if(str[i][0] == 'D') DeleteEdge(G,str[i][1]-'0',str[i][2]-'0');
else if(str[i][0] == 'Q')
{
if(Query(G,str[i][1]-'0',str[i][2]-'0')) cout << "Y" << endl;
else cout << "N" << endl;
}
}
return 0;
}
Followed by: Post your reply here: |
All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator